【问题标题】:Class inheriting itself? Question about inheritance and the super() method [duplicate]类继承自己?关于继承和 super() 方法的问题 [重复]
【发布时间】:2020-10-21 15:42:23
【问题描述】:

我有一个关于 Python 中的类、子类和继承的问题。

我使用 Tkinter 进行 GUI 开发已经有一段时间了,并决定学习如何使用 Kivy。在 Kivy 文档中,我遇到了一行对我没有任何意义的代码。如下(注意,GridLayout是我从kivy模块导入的一个类):

class LoginScreen(GridLayout):

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)

super 调用 LoginScreen 和 self 而不是 GridLayout 真的让我很困惑!类是否继承自身?怎么回事?

在 Tkinter 中我会写类似的东西(再次注意,tk.Frame 是从 Tkinter 模块导入的类):

class LoginScreen(tk.Frame)
   
    def __init__(self, parent):
        super().__init__(parent)

当我输入这两个示例时,我注意到我没有向super() 传递任何内容。 super方法的默认参数是类名和self吗?即上述类似于写作...

class LoginScreen(tk.Frame):

    def __init__(self, parent):
        super(LoginScreen, self).__init__(parent) 

如果它们不同,你能解释为什么它们不同,但如果它们相同,你能更深入地解释一下super() 是如何做的(不仅仅是它继承了父类)?

【问题讨论】:

    标签: python class oop tkinter kivy


    【解决方案1】:

    是的,这些是super 的默认参数,您可以在docs 的示例中看到:

    class C(B):
        def method(self, arg):
            super().method(arg)    # This does the same thing as:
                                   # super(C, self).method(arg)
    

    (评论不是我的,原来的例子是这样的)

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 2020-07-24
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2016-07-24
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多