初始化 child class 中使用的属性 parent class

Initializing an attribute in a child class that is used in the parent class

我正在使用第 3 方 Python 库 (wxPython),它的一个模块中有一个错误 class .
有问题的代码部分如下所示:

def OnText(self, event):
    value = self.GetValue()
    if value != self.__oldvalue:
        pass  # Here some more code follows ...
    self.__oldvalue = value

问题是if语句,因为在第一次调用这个方法时self.__oldvalue还没有初始化。因此,在库开发人员修复此错误之前,我认为我可以通过一些解决方法来解决此问题。我只是想从那个错误的 class 派生一个 child class 并在这个构造函数中初始化 self.__oldvalue

class MyIntCtrl(wx.lib.intctrl.IntCtrl):
    def __init__(self, *args, **kw):
        self.__oldvalue = None
        super().__init__(*args, **kw)

但是,现在当我使用这个新的 class MyIntCtrl 而不是原来的 IntCtrl class 时,我确实得到了与以前完全相同的错误:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/wx/lib/intctrl.py", line 509, in OnText
    if value != self.__oldvalue:
AttributeError: 'MyIntCtrl' object has no attribute '_IntCtrl__oldvalue'

现在我想知道:我做错了什么,我还能如何在 child class 中解决这个问题?

class 中以 __(双下划线)开头的任何成员都是私有的,您可以使用单下划线 _ 或不在命名中使用下划线,以便在派生 classes.

class Parent:
    def __init__(self):
        self.__private_field = "private field"
        self._protected_field = "protected field"
        self.public_field = "public field"

class Child(Parent):
    def __init__(self):
        pass

    def do(self):
        print(self.__private_field) # It will throw exception
        print(self._protected_field) # It will not throw exception
        print(self.public_field) # It will not throw exception

或者您可以绕过 private/protected 成员,像这样称呼他们:

print(_Parent__private_field)