||
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
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
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-9-19 14:55
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社