簡體   English   中英

super() 失敗並出現錯誤:TypeError “argument 1 must be type, not classobj” 當父級不繼承自對象時

[英]super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

我收到一些我無法弄清楚的錯誤。 任何線索我的示例代碼有什么問題?

class B:
    def meth(self, arg):
        print arg

class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

我從“超級”內置方法的幫助中獲得了示例測試代碼。

這是錯誤:

Traceback (most recent call last):
  File "./test.py", line 10, in ?
    print C().meth(1)
  File "./test.py", line 8, in meth
    super(C, self).meth(arg)
TypeError: super() argument 1 must be type, not classobj

僅供參考,這是python本身的幫助(超級):

Help on class super in module __builtin__:

class super(object)
 |  super(type) -> unbound super object
 |  super(type, obj) -> bound super object; requires isinstance(obj, type)
 |  super(type, type2) -> bound super object; requires issubclass(type2, type)
 |  Typical use to call a cooperative superclass method:
 |  class C(B):
 |      def meth(self, arg):
 |          super(C, self).meth(arg)
 |

您的問題是 B 類未聲明為“新型”類。 像這樣改變它:

class B(object):

它會起作用。

super()和所有子類/超類的東西只適用於新式類。 我建議您養成始終在任何類定義上鍵入該(object)的習慣,以確保它是一個新型類。

舊式類(也稱為“經典”類)始終是classobj類型; 新式類的類型為type 這就是您看到錯誤消息的原因:

TypeError: super() argument 1 must be type, not classobj

試試這個,看看你自己:

class OldStyle:
    pass

class NewStyle(object):
    pass

print type(OldStyle)  # prints: <type 'classobj'>

print type(NewStyle) # prints <type 'type'>

請注意,在 Python 3.x 中,所有類都是新樣式的。 您仍然可以使用舊式類的語法,但您會得到一個新式類。 所以,在 Python 3.x 中你不會有這個問題。

此外,如果您無法更改 B 類,則可以使用多重繼承來修復錯誤。

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

如果python版本是3.X就可以了。

我認為您的python版本是2.X,添加此代碼時超級會起作用

__metaclass__ = type

所以代碼是

__metaclass__ = type
class B:
    def meth(self, arg):
        print arg
class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)
print C().meth(1)

當我使用 python 2.7 時,我也遇到了發布的問題。 它在 python 3.4 上工作得很好

為了讓它在 python 2.7 中工作,我在我的程序頂部添加了__metaclass__ = type屬性並且它起作用了。

__metaclass__ :它簡化了舊式類和新式類的轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM