python - Obtaining object reference for a method using getattr -
say, have next class called test method called start
>>> class test: ... def __init__(self, *args, **kwargs): ... pass ... def start(self): ... pass ... now, have standalone independent function called func
>>> def func(): ... print 'this func , not method!!!' ... >>> [1] now, t.start method of instance of __main__.test belong 0xb769678c
>>> t = test() >>> t.start <bound method test.start of <__main__.test instance @ 0xb769678c>> >>> [2] func function belong location 0xb767ec6c
>>> func <function func @ 0xb767ec6c> >>> now, can extract __module__ t.start , func using builtin __module__. not surprisingly, func , t.start belong same module i.e. __main__
>>> func.__module__ '__main__' >>> t.__module__ '__main__' >>> [3] now, lets store __module__ t.start in variable obj
>>> obj = __import__(t.start.__module__) >>> obj <module '__main__' (built-in)> >>> now, utilize getattr() func handle <function func @ 0xb767ec6c> function func follows , output of getattr() identical [2]
>>> print getattr(obj, 'func') <function func @ 0xb767ec6c> >>> >>> print getattr(__import__('__main__'), 'func') <function func @ 0xb767ec6c> >>> question: how utilize getattr() , module name [3] handle of test.start [1] should <bound method test.start of <__main__.test instance @ 0xb769678c>>
when tried using getattr() on 't.start' got next traceback
>>> print getattr(obj, 'test.start') traceback (most recent phone call last): file "<stdin>", line 1, in <module> attributeerror: 'module' object has no attribute 'test.start' >>> >>> >>> print getattr(__import__('__main__'), 'test.start') traceback (most recent phone call last): file "<stdin>", line 1, in <module> attributeerror: 'module' object has no attribute 'test.start' >>> in other words, have 2 info me.
__import__('__main__') the sting 'test.start' now, how handle t.start (note instance here) should <bound method test.start of <__main__.test instance @ 0xb769678c>>
i'm not sure if understand question(s), think want:
class test: def __init__(self, *args, **kwargs): pass def start(self): pass def func(): print 'this func , not method!!!' t = test() module = __import__(t.start.__module__) print vars(module)['test'].start print vars(module)['func'] print vars(module)['t'].start output:
class="lang-none prettyprint-override"><unbound method test.start> <function func @ 0x00ba67f0> <bound method test.start of <__main__.test instance @ 0x00bac170>> python function object reference getattr
No comments:
Post a Comment