【发布时间】: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() 如何工作的想法都很好