1

I need to find a method on a super() object by name. This works when using the "dot operator" notation: super(self.__class__,self).p. However, I need to do that dynamically, something like super(self.__class__,self)["p"], which does not work.

I tried to use __getattr__, but super object does not have that method. And super(self.__class__,self).__getattribute__("p") returns self.p instead super().p.

How to do that correctly and elegantly?

For instance:

class A(object):
    def p (self):
        skip

class B(object):
    def p (self):
        skip

class AB (A,B):
    def p (self):
        skip

ab = AB()
o = super(ab.__class__, ab)

print dir(o)
print o.__getattribute__("p").__code__
print o.p.__code__

This code outputs:

['__class__', '__delattr__', '__doc__', '__format__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__
', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__']
<code object p at 000000000205f2b0, file "b.py", line 10>  # AB.p
<code object p at 0000000000361cb0, file "b.py", line 2>   # A.p
xarx
  • 627
  • 1
  • 11
  • 27
  • 1
    ...what? Could you give a less abstract example of what you're trying to achieve? Also, passing `self.__class__` to `super` is a bad idea (see e.g. http://stackoverflow.com/q/4235078/3001761). – jonrsharpe Apr 02 '16 at 08:38
  • @jonrsharpe He's not using self.__class__ inside the class. It will not cause any problem. – Bharel Apr 02 '16 at 08:47
  • @Bharel actually we can't see whether or not they are, because of the oh-so-helpful `snip`. But it seems odd to use `ab.__class__` instead of `AB`. – jonrsharpe Apr 02 '16 at 08:48

1 Answers1

2

What you're looking for is getattr(). This works:

>>> getattr(o, "p")
<bound method A.p of <__main__.AB object at 0x0000000000AA8160>>

By using __getattribute__() directly, you lose the wrapping super() does to the object. You should always use getattr() for getting methods or other attributes. Generally, going directly to __dunder__ methods is discouraged if there are other options.

Bharel
  • 23,672
  • 5
  • 40
  • 80
  • Exactly, thanks a lot. I've spend a lot of time by figuring out how to do that, but without success. – xarx Apr 02 '16 at 08:51