In python, how can I determine which class is a superobject?

Those. if i have a class MyClass and i do super (MyClass). init , how can I tell which init class will be called?

Some code to illustrate:

class MyClass(OtherClass, ThirdClass):
    def __init__(self):
        mySuper = super(MyClass)
        if mySuper == SomeClass:
           # doesn't work - mySuper is a super object (not a normal class object)
        if mySuper.__init__ == SomeClass.__init__:
           # doesn't work - mySuper.__init__ is a super-method-wrapper object
        if mySuper.__thisclass__ == SomeClass:
           # doesn't work - __thisclass__ is set to be MyClass, not the "parent" class


Any ideas?


If I hadn’t scored points here yet, I would probably delete this question as it is not very useful and has the potential to cause bad habits.

As sven-marnach points out , I'm using the one-argument version super(MyClass)

instead of the more useful two-argument version super(MyClass, self)

... and now I have no idea why I wanted to do this. My best guess is that I was still not sure of the correct usage super

at the time.

If you are using the two-argument version, then the second check works - with the warning you need to get .im_func

, that is:

        if mySuper.__init__.im_func == SomeClass.__init__.im_func:


See Determine if super () .__ new__ will be a .__ new__ object in Python 3? for an example of why such a check is useful ...


source to share

1 answer

You can extract the wrapped class using

mro = my_super.__self_class__.mro()
wrapped_class = mro[mro.index(my_super.__thisclass__) + 1]


It looks complicated, but I also find it pretty pointless to do it.

Edit . I just noticed that you don't get through self

to super()

. In this case, you can use

wrapped_class = my_super.__thisclass__.mro()[1]


The question remains: why would you do this?



All Articles