我有以下课程:
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,但是到目前为止,我真的别无选择。
这是由于名称修改。的__virt_method
将被Python改名内部以_A__virt_method
在基类和_B__virt_method
派生类:
格式的任何标识符
__spam
(至少两个前导下划线,至多一个尾随下划线)在文本上均替换为_classname__spam
,其中classname是当前的类名,其中前导下划线被去除。
将方法重命名为_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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句