Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python super() raises TypeError

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?

like image 664
Geo Avatar asked Jan 28 '09 20:01

Geo


People also ask

What does super () do in Python?

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.

What is the effect of calling super () __ Init__?

__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 .

What does super () __ init __ do in Python?

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.

How do you check super class in Python?

You can use a issubclass function. Attention: issubclass(A, A) evaluates to True .


1 Answers

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 
like image 179
Serafina Brocious Avatar answered Oct 14 '22 06:10

Serafina Brocious