Can create a def in a python class that can be called what was ever named def even if def did not exist

I want to do something like this:

class MyClass(Object):
    def ****(self):
        print self.__name __

MyClass.test()
->test

MyClass.whatever()
->whatever

      

This way you can call any method and it prints the name.

+3


source to share


1 answer


Inject a method __getattr__()

into your class to intercept attempts to access unknown attributes and return a function (which you could bind to the class):

class MyClass(object):
    def __getattr__(self, name):
        def echo():
            return name
        return echo

      

Returns unrelated functions with no instance reference.

To do this, you need to create an instance:

>>> class MyClass(object):
...     def __getattr__(self, name):
...         def echo():
...             return name
...         return echo
... 
>>> instance = MyClass()
>>> instance.test()
'test'
>>> instance.whatever()
'whatever'

      



You can bind a function to an instance (so that it gets self

) by manually invoking the handle protocol , calling __get__

on the function before returning:

class MyClass(object):
    def __getattr__(self, name):
        def echo(self):
            return '{}.{}'.format(type(self).__name__, name)
        return echo.__get__(self, type(self))

      

With access to, self

we can print a little more information:

>>> class MyClass(object):
...     def __getattr__(self, name):
...         def echo(self):
...             return '{}.{}'.format(type(self).__name__, name)
...         return echo.__get__(self, type(self))
... 
>>> instance = MyClass()
>>> instance.test()
'MyClass.test'
>>> instance.whatever()
'MyClass.whatever'

      

+2


source







All Articles