Python: query a class's parent-class after multiple derivations ("super()" does not work)
Posted
by
henry
on Stack Overflow
See other posts from Stack Overflow
or by henry
Published on 2011-01-10T10:19:29Z
Indexed on
2011/01/10
17:53 UTC
Read the original article
Hit count: 340
Hi, I have built a class-system that uses multiple derivations of a baseclass (object->class1->class2->class3):
class class1(object):
def __init__(self):
print "class1.__init__()"
object.__init__(self)
class class2(class1):
def __init__(self):
print "class2.__init__()"
class1.__init__(self)
class class3(class2):
def __init__(self):
print "class3.__init__()"
class2.__init__(self)
x = class3()
It works as expected and prints:
class3.__init__()
class2.__init__()
class1.__init__()
Now I would like to replace the 3 lines
object.__init__(self)
...
class1.__init__(self)
...
class2.__init__(self)
with something like this:
currentParentClass().__init__()
...
currentParentClass().__init__()
...
currentParentClass().__init__()
So basically, i want to create a class-system where i don't have to type "classXYZ.doSomething()".
As mentioned above, I want to get the "current class's parent-class".
Replacing the three lines with:
super(type(self), self).__init__()
does NOT work (it always returns the parent-class of the current instance -> class2) and will result in an endless loop printing:
class3.__init__()
class2.__init__()
class2.__init__()
class2.__init__()
class2.__init__()
...
So is there a function that can give me the current class's parent-class?
Thank you for your help!
Henry
--------------------
Edit:
@Lennart ok maybe i got you wrong but at the moment i think i didn't describe the problem clearly enough.So this example might explain it better:
lets create another child-class
class class4(class3):
pass
now what happens if we derive an instance from class4?
y = class4()
i think it clearly executes:
super(class3, self).__init__()
which we can translate to this:
class2.__init__(y)
this is definitly not the goal(that would be class3.__init__(y)
)
Now making lots of parent-class-function-calls - i do not want to re-implement all of my functions with different base-class-names in my super()-calls.
© Stack Overflow or respective owner