比如说,我有以下 class
叫Test
与 method
叫start
>>> class Test:
... def __init__(self, *args, **kwargs):
... pass
... def start(self):
... pass
...
现在,我有一个独立的function
叫func
>>> def func():
... print 'this is a func and not a method!!!'
...
>>>
[1]
现在,t.start
是 method
的instance of __main__.Test
属于0xb769678c
>>> t = Test()
>>> t.start
<bound method Test.start of <__main__.Test instance at 0xb769678c>>
>>>
[2]
func
是 function
属于位置0xb767ec6c
>>> func
<function func at 0xb767ec6c>
>>>
现在,我们可以提取 __module__
来自t.start
和func
通过使用内置 __module__
。毫不奇怪,func
和t.start
属于同一个module
即__main__
>>> func.__module__
'__main__'
>>> t.__module__
'__main__'
>>>
[3]
现在,让我们存储 __module__
对于 t.start
在变量 obj
中
>>> obj = __import__(t.start.__module__)
>>> obj
<module '__main__' (built-in)>
>>>
现在,我使用getattr()
获取func
handle <function func at 0xb767ec6c>
对于功能func
如下,输出getattr()
是identical
至 [2]
>>> print getattr(obj, 'func')
<function func at 0xb767ec6c>
>>>
>>> print getattr(__import__('__main__'), 'func')
<function func at 0xb767ec6c>
>>>
问题:
如何使用getattr()
和模块名称 [3] 来获取 Test.start
的句柄[1] 应该是<bound method Test.start of <__main__.Test instance at 0xb769678c>>
当我尝试使用getattr()
时上't.start'
我得到以下Traceback
>>> print getattr(obj, 'Test.start')
Traceback (most recent 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 call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Test.start'
>>>
也就是说,我身上有两个数据。他们是
-
__import__('__main__')
- 刺痛
'Test.start'
现在,我如何获取 t.start
的句柄(注意这里的instance
)应该是<bound method Test.start of <__main__.Test instance at 0xb769678c>>
最佳答案
我不确定我是否理解您的问题,但我认为这符合您的要求:
class Test:
def __init__(self, *args, **kwargs):
pass
def start(self):
pass
def func():
print('this is a func and not a method!!!')
t = Test()
module = __import__(t.start.__module__)
print(vars(module)['Test'].start)
print(vars(module)['func'])
print(vars(module)['t'].start)
(Python 3)输出:
<function Test.start at 0x00E52460>
<function func at 0x00E524F0>
<bound method Test.start of <__main__.Test object at 0x008DF670>>
关于python - 使用 getattr 获取方法的对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14823691/