为什么 Super() 返回 TypeError: super(type, obj): obj 必须是类型的实例或子类型



我正在使用以下代码玩超级函数:

class A:
@staticmethod
def hello(string):
print('hello '+string)
class B(A):
@staticmethod
def greeting(string):
super().hello(string)
print('How are you?')
x = B
x.greeting('mate')

但是,上面给了我以下错误:类型错误:super(type, obj(:obj 必须是类型的实例或子类型

我已经在S.O上寻找与此相关的其他问题,但它们没有解决这个特定问题。

为什么会这样?x 不是类型的子类型吗?

提前非常感谢

而不是使用超级函数,你可以直接给出超级函数的名字,即A。这是因为在这种情况下我们不能使用 self 关键字。但是,如果你想使用 super((,那么传递 super(B, B(。

# First alternative
class A:
@staticmethod
def hello(string):
print('hello '+string)
class B(A):
@staticmethod
def greeting(string):
A.hello(string)
print('How are you?')
x = B
x.greeting('mate')
# second alternative
class A:
@staticmethod
def hello(string):
print('hello '+string)
class B(A):
@staticmethod
def greeting(string):
super(B, B).hello(string)
print('How are you?')
x = B
x.greeting('mate')

#either way, you will get following
output>>>hello mate
How are you?

相关内容

最新更新