【问题标题】:Why does Super() return TypeError: super(type, obj): obj must be an instance or subtype of type为什么 Super() 返回 TypeError: super(type, obj): obj must be an instance or subtype of type
【发布时间】:2019-10-15 15:51:54
【问题描述】:

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

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 必须是类型的实例或子类型

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

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

在此先感谢

【问题讨论】:

  • 我认为这可能与 @staticmethod 装饰器有关。
  • 另外,当您尝试创建实例时,不要忘记调用类构造函数。也就是说,您可能想输入x = B() 而不是x = B

标签: python


【解决方案1】:

你可以直接给超级函数名称而不是使用超级函数,即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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 2019-01-05
    • 2014-08-29
    • 2021-05-12
    • 2021-11-23
    • 2021-08-21
    • 1970-01-01
    • 2017-08-14
    相关资源
    最近更新 更多