使用 2 参数形式调用 super() 与直接引用该方法并手动传入 "self" 有何不同?
How does calling super() with the 2-argument form differ from directly referencing the method and passing in "self" manually?
有点奇怪的问题,请考虑以下代码:
class A:
def mymethod(self):
return "mymethod from class A"
class B(A):
def mymethod(self):
return "mymethod from class B"
class C(B):
# in this class I want "mymethod" to return the same string returned from mymethod in the A class, with 2 exclamation points (!!) appended
# obviously this is a simplified example with dumb logic
def mymethod(self):
ss = super(B, self).mymethod()
# OR
ss = A.mymethod(self)
return ss + " !!"
我在 OOP 方面相当缺乏经验,所以如果答案非常明显,请原谅。
据我所知,这两种方法之间没有区别,因此我无法理解 super()
如何在 class 方法中发挥作用。
使用super(B, self)
消除了一定程度的依赖。如果 B
的定义更改为使用不同的超级 class,您将自动调用该 class 的方法。如果您 hard-code A.mymethod(self)
,则需要在重新定义 B
时更新它。
有点奇怪的问题,请考虑以下代码:
class A:
def mymethod(self):
return "mymethod from class A"
class B(A):
def mymethod(self):
return "mymethod from class B"
class C(B):
# in this class I want "mymethod" to return the same string returned from mymethod in the A class, with 2 exclamation points (!!) appended
# obviously this is a simplified example with dumb logic
def mymethod(self):
ss = super(B, self).mymethod()
# OR
ss = A.mymethod(self)
return ss + " !!"
我在 OOP 方面相当缺乏经验,所以如果答案非常明显,请原谅。
据我所知,这两种方法之间没有区别,因此我无法理解 super()
如何在 class 方法中发挥作用。
使用super(B, self)
消除了一定程度的依赖。如果 B
的定义更改为使用不同的超级 class,您将自动调用该 class 的方法。如果您 hard-code A.mymethod(self)
,则需要在重新定义 B
时更新它。