簡體   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