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 super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
__init__() of the superclass ( Square ) will be called automatically. super() returns a delegate object to a parent class, so you call the method you want directly on it: super(). area() . Not only does this save us from having to rewrite the area calculations, but it also allows us to change the internal .
Understanding Python super() with __init__() methods When this method is called it allows the class to initialize the attributes of the class. In an inherited subclass, a parent class can be referred with the use of the super() function.
You can use a issubclass function. Attention: issubclass(A, A) evaluates to True .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With