【问题标题】:The init values did not inherited to another class with super()初始化值没有用 super() 继承到另一个类
【发布时间】:2019-10-17 08:46:34
【问题描述】:

我构建了 2 个类。第一个类具有自己的初始化值,另一个类将从第一个类继承初始化值。我想知道我是否正确理解了 super() 的用法。

class testing(testing_2):
    def __init__(self, name, c):
        super().__init__(name, c)

    def check(self):
        print(super().name)

class testing_2:
    def __init__(self, name, c):
        self.name = name
        self.c = c

tt = testing("tester", "check")
tt.check()

我认为我的代码应该打印了“测试器”,因为我用名称和 c 初始化了测试类。因为测试类继承自 testing_2 所以我们可以打印名称。我是不是混淆了什么?

我的期望是:

testing_2 将从 testing 中获取值,我们可以在 testing 中打印 testing_2 的值。

【问题讨论】:

  • 您不需要使用super 来访问实例变量。你应该可以在testing 中使用self.name。您还需要以相反的方式定义您的类。
  • 而且由于testing.__init__ 本身并没有做任何事情,您可以完全省略它。
  • 非常感谢。我是如此专注于使用超级方法,以至于我搞砸了我的知识。顺便说一句,任何关于 super() 如何工作的想法都很好

标签: python super


【解决方案1】:

简化它:

class A:
    def __init__(self, name, c):
        self.name = name
        self.c = c


class B(A):
    def check(self):
        print(self.name)


tt = B("tester", "check")
tt.check()

B 对象将具有与A 对象相同的所有内容,因为它继承它们。如果B 没有任何用处,则无需在B 上实现__init__。您可以直接访问self.name,就像在A 中一样。具有该属性的对象是self。它设置在self,您可以使用self 访问它。

记住,self对象实例,而不是类。在做B(...)时,A.__init__(self, ...)中的self实际上是B的一个实例。

如果您要覆盖父方法,则只需要显式使用super,例如:

def __init__(self, name, c):
    super().__init__(name, c)

这里__init__覆盖,为了执行父级的__init__,您需要通过super 访问它。只需 self.__init__(name, c) 将访问孩子的 __init__ 方法,您将在无限递归循环中调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2018-02-02
    • 1970-01-01
    相关资源
    最近更新 更多