Python __init__() 如何不覆盖重要功能?

Python __init__() how don't override important functionality?

我需要在 class 中添加另一个选项,一个简单的 'edit=False'。无需完全覆盖 init()。 我找到了这段为 kivy 写的代码:

class TitleBox(BoxLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(TitleBox, self).__init__(**kwargs)

但是当我尝试为我的目的进行编辑时,我收到:"TypeError: init() takes at most 2 arguments (3 given)"

class Person_Dialog(tkSimpleDialog.Dialog):
    def __init__(self, edit=False, **kwargs):
        super(Person_Dialog, self).__init__(**kwargs)
        self.edit = edit

给定 __init__ 签名:

def __init__(self, edit=False, **kwargs):

当你这样做时:

add = Person_Dialog(root, 'Add person')

Python 创建一个实例并将其分配给 self 参数。然后它将 root 分配给 edit 参数。然后它需要 'Add a person' 并且找不到其他 positional 参数来分配给它。

要解决此问题,请向 __init__ 添加另一个参数:

class Person_Dialog(tkSimpleDialog.Dialog):
    def __init__(self, parent, edit=False, **kwargs): # added parent argument
        super(Person_Dialog, self).__init__(parent, **kwargs)
        self.edit = edit

请注意,我们还将 parent 传递给 superclass 因为 tkSimpleDialog.Dialog 具有此签名 __init__(self, parent, title=None).

不幸的是,您的代码现在因 TypeError: must be type, not classobj 而失败,因为 tkSimpleDialog.Dialog 是旧样式 class 并且您不能将 super() 与旧样式一起使用 class是的。 (Python 3 取消了旧样式 classes,所以你不会在那里遇到这个问题。)

因此,要解决此问题,请将对 super() 的调用替换为对 superclass:

的直接引用
class Person_Dialog(tkSimpleDialog.Dialog):
    def __init__(self, parent, edit=False, **kwargs):
        # referencing the superclass directly
        tkSimpleDialog.Dialog.__init__(self, parent, **kwargs) 
        self.edit = edit

现在您的代码可以运行了。