我有以下类(class):
class A:
def __init__(self):
#base constructor implementation
pass
def __virt_method(self):
raise NotImplementedError()
def public_method(self):
self.__virt_method()
class B(A):
def __init(self):
A.__init__(self)
#derived constructor implementation
pass
def __virt_method(self):
#some usefull code here
pass
我正在尝试像这样使用它,假设要调用重写的方法:
b = B()
b.public_method()
但相反,我得到了
NotImplementedError
(我做错了什么还是 Python (2?) 问题?我知道 Python 2 已被弃用,最好使用 Python 3,但现在我真的别无选择。
最佳答案
这是由于 name mangling 。 __virt_method
会被 Python 在内部重命名为基类中的 _A__virt_method
和派生类中的 _B__virt_method
:
Any identifier of the form
__spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam
, where classname is the current class name with leading underscore(s) stripped.
将该方法重命名为
_virt_method
(只有一个下划线),它将起作用:class A:
def __init__(self):
# base constructor implementation
pass
def _virt_method(self):
raise NotImplementedError()
def public_method(self):
self._virt_method()
class B(A):
def __init(self):
A.__init__(self)
# derived constructor implementation
pass
def _virt_method(self):
# some useful code here
pass
关于python - 如何调用派生类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58999534/