我的代码基本上是这样的
class main:
def __init__(self):
pass
def unneededfunction(self):
print("unneeded thing")
class notmain(main):
def __init__(self):
pass
#code for getting rid of unneededfunction here
如何去掉notmain.unneeded函数?(也就是说,调用它会导致错误)
如果你不希望notmain
有unneededfunction
,那么notmain
不应该是main
的子类。用这种方式来对抗系统就违背了继承的全部意义。
如果你真的坚持这样做,notmain
可以重新定义unneededfunction
,并引发与unneededfunction
不存在时相同的异常,AttributeError
。但是,你又一次违背了我的意愿。
除此之外,你不能从notmain
中删除unneededfunction
,因为notmain
不拥有那个方法,它的父类main
拥有。
你需要删除吗?(即,它抛出一个属性错误)。或者你能得到部分继承吗?
这里的第一个答案应该解决后者:如何执行部分继承
如果你只是想让它在调用时抛出错误,这应该可以工作:
class notmain(main):
def __init__(self):
pass
def unneededfunction(self):
raise NotImplementedError("explanation")
或者你可以尝试在这里讨论的Mixin方法来构建类:有可能用Python做部分继承吗?