如果我运行这段代码:
class Super:
def __init__(self, name):
self.name = name
class Sub(Super):
def publ(self):
print("works")
a = Sub()
按计划它成功失败并显示此消息:
TypeError: __init__() takes exactly 2 arguments (1 given)
但它给了我一个烦人的问题:
有关参数条目的子类要求的信息存储在哪里?我的意思是 SUB() 如何知道它需要“名称”作为参数? 定义它如何从 Super() 继承“知识”的机制是什么。
请您参考如下方法:
Python 教程 has a section on inheritance .
if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.
当您调用 Sub() 时,解释器会在类对象中查找名为 __init__ 的属性。如果它找到一个,它将使用它。如果找不到它(在您的示例中就是这种情况),它将搜索该类的基类。在您的示例中,它找到了从类 Super 继承的 __init__ 方法。解释器将继续调用该方法。
您可以通过以下任一方式修复您的示例:
a = Sub('John Doe')
或:
class Sub(Super):
def __init__(self):
super(Sub, self).__init__("My Name Is Sub")
def publ(self):
print("works")
