我有以下几门课:
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
我尝试这样使用它,假设要调用的重写方法:
^{pr2}$但是我得到了NotImplementedError
(我是做错了什么还是Python(2?)有问题吗?我知道Python2已被弃用,最好使用Python3,但现在我真的别无选择。在
问题是,名称以}。在
__
开头的方法,比如__virt_method
的方法名称有误。基本上,根据它们所在的类,它们的名称被转换为A__virt_method
或{如果将该方法重命名为
_virt_method
,则一切都将按预期工作这是由于name mangling。Python将在内部将}重命名为:
__virt_method
重命名为基类中的_A__virt_method
,并在派生类中将{将该方法重命名为
_virt_method
(只有一个下划线),它将起作用:如果任何变量以''uuu'开头,python就知道这个变量实际上是一个私有变量,因此它使用一个名为
name mangling
的概念来阻止对该变量的直接访问。如果变量以'\'开头供内部使用或仅限于本地范围(当from something import *
时不加载)。在相关问题 更多 >
编程相关推荐