Reputation: 23624
So I've been messing around in python and I don't understand what the shell is going on with this.
I start by writing these classes in this order.. comments are my understanding of what's happening:
# class A1 inherits object
class A(object):
pass
# class B1 inherits A1, object
class B(A):
def a(self):
print "b",
super(B, self).a()
# class A2 inherits B1, A1, object
class A(B):
def a(self):
print "a",
super(A, self).a()
# class B2 inherits A2, B1, A1, object
class B(A):
def a(self):
print "b",
super(B, self).a()
When I create an instance of A
which is A2 and call A.a
,
>>> a = A()
>>> a.a()
a b
Traceback (most recent call last):
File "<pyshell#263>", line 1, in <module>
a.a()
File "<pyshell#258>", line 4, in a
super(A, self).a()
File "<pyshell#256>", line 4, in a
super(B, self).a()
TypeError: super(type, obj): obj must be an instance or subtype of type
I thought the error would be (as Kevin suggests) AttributeError: A instance has no attribute 'a'
because I expected A2 > B1 > A1 (no a function) Crash
Even more curious,. when I now create an instance of B
, even more unexpected results happens..
>>> b = B()
>>> b.a()
b a b a b a b a b a b a b a b a b a b a b a b a b a b a b a b a b a b a b a b a ...
Shouldn't this crash the same way A
did, but just one function more?
What?
Upvotes: 3
Views: 2871
Reputation: 23624
After creating class A2
and class B2
, the lines
super(B, self).a()
super(A, self).a()
Use the type A2
and B2
respectively for all class functions, A2.a
,B1.a
,B2.a
..
This means that when I call A2.a
, the super calls the base class B1.a
. In B1.a
the function attempts to use the super
function with type B2
and a instance of A2
.. thus giving a obj must be an instance or subtype of type
error.
When I call B2.a
, the super calls A2.a
then calls B1.a
where upon calling super
with type B2
and an instance of B2
once again calls the A2.a
function... Where it will loop indefinitely until a recursion error is thrown!
So it ends up only looking like a circular inheritance, when really its just two circular functions given a particular parameter.
Upvotes: 1