在 grand child class 中调用祖父母方法
Call grandparent method in grand child class
抱歉,这可能是个愚蠢的问题,但让我很困惑。假设我们有以下 classes:
class A():
def say(self):
print("A")
class B(A):
def say(self):
print("B")
class C(B):
def say(self,*args, **kwargs):
return super(C, self).say(*args, **kwargs)
我正在访问 child 中的 parent 方法,它打印 B
,但我想像我们一样访问 class A
中的方法从 class B
.
获取访问权限
我知道我们可以在class B中添加super
,但我不想修改class B
。那么是否有任何选项可以直接在 class C
中从 A
获取方法?
您可以像这样调用 A.say(self)
:
class A():
def say(self):
print("A")
class B(A):
def say(self):
print("B")
class C(B):
def say(self):
A.say(self)
B.say(self)
print("C")
然后从终端测试它:
>>> a = A()
>>> a.say()
A
>>> b = B()
>>> b.say()
B
>>> c = C()
>>> c.say()
A
B
C
注意:我删除了 args
和 kwargs
,因为 A
和 B
类 没有使用这些参数。如果你想让 say
一路走下去,尽管只需调用 A.say(self, *args, **kwargs)
如果 A.say
return 你也可以 return [=20] =]
抱歉,这可能是个愚蠢的问题,但让我很困惑。假设我们有以下 classes:
class A():
def say(self):
print("A")
class B(A):
def say(self):
print("B")
class C(B):
def say(self,*args, **kwargs):
return super(C, self).say(*args, **kwargs)
我正在访问 child 中的 parent 方法,它打印 B
,但我想像我们一样访问 class A
中的方法从 class B
.
我知道我们可以在class B中添加super
,但我不想修改class B
。那么是否有任何选项可以直接在 class C
中从 A
获取方法?
您可以像这样调用 A.say(self)
:
class A():
def say(self):
print("A")
class B(A):
def say(self):
print("B")
class C(B):
def say(self):
A.say(self)
B.say(self)
print("C")
然后从终端测试它:
>>> a = A()
>>> a.say()
A
>>> b = B()
>>> b.say()
B
>>> c = C()
>>> c.say()
A
B
C
注意:我删除了 args
和 kwargs
,因为 A
和 B
类 没有使用这些参数。如果你想让 say
一路走下去,尽管只需调用 A.say(self, *args, **kwargs)
如果 A.say
return 你也可以 return [=20] =]