python - 如何调用派生类方法?

标签 python python-2.7

我有以下类(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/

相关文章:

Python,删除以特定字符开头的单词

python - 如何在 Google App Engine Python 服务器上启用 CORS?

python - 为什么python xmlrpc调用在通过apache运行时会得到PermissionError?

python - 如何根据另一个包含通配符的列表过滤列表?

python - python中的求和求和

python - 通过Python中的同一函数解析(删除多余的空格,编码)多个属性

python - 无法在Python中使用.format()打印time()

python - 应用程序退出后未设置剪贴板?

python - 通过python删除mysql中的行

python - 在函数式编程(或其他方式)中递归时,使用显式状态变量的好处/限制是什么?