function - Can create a def in python class which can be called what ever the def name even if the def didn't exist -
i'm looking this:
class myclass(object): def ****(self): print self.__name __ myclass.test() ->test myclass.whatever() ->whatever
so can call method , prints name.
implement __getattr__()
method on class intercept access attempts on unknown attributes, , return function (which bind class):
class myclass(object): def __getattr__(self, name): def echo(): return name return echo
this returns unbound functions, no reference instance.
you need create instance first work:
>>> class myclass(object): ... def __getattr__(self, name): ... def echo(): ... return name ... return echo ... >>> instance = myclass() >>> instance.test() 'test' >>> instance.whatever() 'whatever'
you can bind function instance (so gets self
passed in) manually invoking descriptor protocol, calling __get__
on 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 self
can print 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'
Comments
Post a Comment