super 有 2 个参数,
super(type, obj_of_type-or-subclass_of_type)
Run Code Online (Sandbox Code Playgroud)
我理解如何以及为什么使用 super ,第二个参数是 obj_of_type 。但我不明白第二个参数是子类的问题。
任何人都可以展示为什么以及如何?
我有代码剪断如下:
class A:
def test(self):
return 'A'
class B(A):
def test(self):
return 'B->' + super(B, self).test()
print(B().test())
Run Code Online (Sandbox Code Playgroud)
输出:B->A
如果我写这样的东西,那么我会得到相同的输出:
class A:
def test(self):
return 'A'
class B(A):
def test(self):
return 'B->' + super().test() # change to super()
print(B().test())
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,我都得到相同的输出。那么,我想知道这两种调用的区别是super什么?使用它们中的任何一个都有什么优点和缺点?
为什么我们使用的时候不需要自引用super().__init__?(比如下面第9行)
class labourers():
def __init__(self,name,department,salary):
self.name = name
self.department = department
self.salary = salary
class managers(labourers):
def __init__(self,name,department,salary,numberofpeople):
super().__init__(name,department,salary)
self.numberofpeople = numberofpeople
Run Code Online (Sandbox Code Playgroud)