繁体   English   中英

为什么 Super() 返回 TypeError: super(type, obj): obj must be an instance or subtype of type

[英]Why does Super() return TypeError: super(type, obj): obj must be an instance or subtype of type

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

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')

但是,上面给了我以下错误: TypeError: super(type, obj): obj must be an instance or subtype of type

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

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

提前谢谢了

除了使用 super function 之外,您还可以直接将 super function 命名为 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?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM