gll89的个人博客分享 http://blog.sciencenet.cn/u/gll89

博文

Python--Super usage

已有 2038 次阅读 2017-12-13 08:26 |个人分类:Python|系统分类:科研笔记

I get some error that I can't figure out. Any clue what is wrong with my sample code?

class B:

   def meth(self, arg):

       print arg

class C(B):

   def meth(self, arg):        

       super(C, self).meth(arg)

       print C().meth(1)

I got the error:

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


Answer:

Your problem is that class B is not declared as a "new-style" class.  Change it like so:

   class B(object):

and it will work.

super() and all subclass/superclass stuff only works with new-style classes.  I recommend you get in the habit of always typing that (object) on any class definition to make sure it is a new-style class.

Old-style classes (also known as "classic" classes) are always of type classobj; new-style classes are of type type.  This is why you got the error message you saw:

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

Try this to see for yourself

       class OldStyle:

         pass

     class NewStyle(object):

         pass

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

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

Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem


https://stackoverflow.com/questions/1713038/super-fails-with-error-typeerror-argument-1-must-be-type-not-classobj

========================================================


The reason we use super is so that child classes that may be using cooperative multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO).

In Python 3, we can call it like this:

class ChildB(Base):

   def __init__(self):        

       super().__init__()

In Python 2, we are required to use it like this:

       super(ChildB, self).__init__()


https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods


============================

Another example of using super

https://www.python-course.eu/python3_inheritance.php



https://blog.sciencenet.cn/blog-1969089-1089410.html

上一篇:DL--Examples of weight Initialization in deep neural network
下一篇:Python--sort numeric string
收藏 IP: 128.227.115.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-9-19 14:55

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部