python - 使用 getattr 获取方法的对象引用

标签 python function object reference getattr

比如说,我有以下 classTestmethodstart

>>> class Test:
...     def __init__(self, *args, **kwargs):
...         pass
...     def start(self):
...         pass
... 

现在,我有一个独立的functionfunc

>>> def func():
...     print 'this is a func and not a method!!!'
... 
>>> 

[1] 现在,t.startmethodinstance of __main__.Test属于0xb769678c

>>> t = Test()
>>> t.start
<bound method Test.start of <__main__.Test instance at 0xb769678c>>
>>> 

[2] funcfunction属于位置0xb767ec6c

>>> func
<function func at 0xb767ec6c>
>>> 

现在,我们可以提取 __module__来自t.startfunc通过使用内置 __module__ 。毫不奇怪,funct.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'
>>> 

也就是说,我身上有两个数据。他们是

  1. __import__('__main__')
  2. 刺痛 '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/

相关文章:

C++ 对象数组。一个元素访问数组中另一个元素的方法

Javascript 对象选项 : function or null

python - 将行添加到 Pandas DataFrame 中的组

python - 如果我的日期在字符串中,我如何在 Python 中对这个列表进行排序?

python - 使用 Python 将二进制文件上传到 postgres 服务器

c - 无法将结构传递给 C 中的线程函数

vba - 如何将当前对象 (Me) 设置为存储在 Visual Basic for Excel 中的数组中的新对象

python - 使用 "pip install magenta"的 Magenta 安装即使在新环境中也有错误

C++ - 调用的 Lua 函数总是返回 0

无法理解如何从 C 中的函数返回字符串