如何调用派生类方法?

2024-06-16 11:00:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下几门课:

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,但现在我真的别无选择。在


Tags: selfbaseinitdefsomepasspublicmethod
3条回答

问题是,名称以__开头的方法,比如__virt_method的方法名称有误。基本上,根据它们所在的类,它们的名称被转换为A__virt_method或{}。在

如果将该方法重命名为_virt_method,则一切都将按预期工作

这是由于name mangling。Python将在内部将__virt_method重命名为基类中的_A__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

如果任何变量以''uuu'开头,python就知道这个变量实际上是一个私有变量,因此它使用一个名为name mangling的概念来阻止对该变量的直接访问。如果变量以'\'开头供内部使用或仅限于本地范围(当from something import *时不加载)。在

In [60]: class A(object):
    ...:     def __init__(self):
    ...:         self.__name = 'Premkumar'
    ...:     

In [61]: premkumar = A()

In [62]: premkumar.__dict__
Out[62]: {'_A__name': 'Premkumar'}

相关问题 更多 >