Calling a method with getattr in Python

Posted by brain_damage on Stack Overflow See other posts from Stack Overflow or by brain_damage
Published on 2010-05-26T23:38:45Z Indexed on 2010/05/26 23:51 UTC
Read the original article Hit count: 264

Filed under:
|
|

How to call a method using getattr? I want to create a metaclass, which can call non-existing methods of some other class that start with the word 'oposite_'. The method should have the same number of arguments, but to return the opposite result.

def oposite(func):
    return lambda s, *args, **kw:  not oposite(s, *args, **kw)


class Negate(type):
    def __getattr__(self, name):
        if name.startswith('oposite_'):
            return oposite(self.__getattr__(name[8:]))        
    def __init__(self,*args,**kwargs):
        self.__getattr__ = Negate.__getattr__


class P(metaclass=Negate):
    def yep(self):
        return True

But the problem is that

self.__getattr__(sth) 

returns a NoneType object.

>>> p = P()
>>> p.oposite_yep()
Traceback (most recent call last):
  File "<pyshell#115>", line 1, in <module>
    p.oposite_yep()
TypeError: <lambda>() takes at least 1 positional argument (0 given)

How to deal with this?

© Stack Overflow or respective owner

Related posts about python

Related posts about metaclass