Python super() 引发 TypeError [英] Python super() raises TypeError

查看:25
本文介绍了Python super() 引发 TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 2.5 中,以下代码引发 TypeError:

<预><代码>>>>X级:定义一个(自我):打印一个">>>Y(X) 类:定义一个(自我):超级(Y,self).a()打印b">>>c = Y()>>>c.a()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 3 行,在一个类型错误:super() 参数 1 必须是类型,而不是 classobj

如果我将 class X 替换为 class X(object),它将起作用.对此有何解释?

解决方案

原因是 super() 仅作用于 新式类,在2.x系列中的意思是从object扩展而来:

<预><代码>>>>X 类(对象):定义一个(自我):打印 'a'>>>Y(X) 类:定义一个(自我):super(Y, self).a()打印'b'>>>c = Y()>>>c.a()一个乙

In Python 2.5, the following code raises a TypeError:

>>> class X:
      def a(self):
        print "a"

>>> class Y(X):
      def a(self):
        super(Y,self).a()
        print "b"

>>> c = Y()
>>> c.a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in a
TypeError: super() argument 1 must be type, not classobj

If I replace the class X with class X(object), it will work. What's the explanation for this?

解决方案

The reason is that super() only operates on new-style classes, which in the 2.x series means extending from object:

>>> class X(object):
        def a(self):
            print 'a'

>>> class Y(X):
        def a(self):
            super(Y, self).a()
            print 'b'

>>> c = Y()
>>> c.a()
a
b

这篇关于Python super() 引发 TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆