Can create a def in a python class that can be called what was ever named def even if def did not exist
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 to share