python2.7 使用super关键词 报错 TypeError: must be type, not classobj 解决办法

Posted on 2013-07-04 14:13:00

python2.7 使用super关键词 报错 TypeError: must be type, not classobj 解决办法

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://yeelone.blog.51cto.com/1476571/971591

 今天遇到这个错误:

Traceback (most recent call last):

  File "t2.py", line 14, in

    print Derived().meth()

  File "t2.py", line 10, in meth

    super(Derived,self).meth()

TypeError: must be type, not classobj

试验代码如下:

1. class Base():
2. def meth(self):
3. print "i'm base"
4. 
5. class Derived(Base):
6. def meth(self):
7. super(Derived,self).meth()
8. print "this is derived"
9. 
10. print Derived().meth()

google了下,发现原因是: super只能用于python的新类中,如果基类是经典类,则会报这个错。 新类和经典类又是什么呢? 新类:所有类都必须要有继承的类,如果什么都不想继承,就继承到object类。 经典类:什么都不用继承的类,如上面的代码就是经典类。所以报错。

1. class Base(object):
2. def meth(self):
3. print "i'm base"

本文出自 “YEELONⒼ” 博客,请务必保留此出处http://yeelone.blog.51cto.com/1476571/971591