可以使用 getattr(obj, attr) 或 inspect.getmembers(obj) 获取对象属性,然后按名称过滤:
import inspect
class Foo(object):
def __init__(self):
self.a = 100
def method(self): pass
foo = Foo()
method_by_getattr = getattr(foo, 'method')
foo_members = inspect.getmembers(foo)
method_by_inspect = [member[1] for member in foo_members
if member[0] == "method"][0]
print (id(method_by_getattr), method_by_getattr, type(method_by_getattr))
print (id(method_by_inspect), method_by_inspect, type(method_by_inspect))
a_by_getattr = getattr(foo, "a")
a_by_inspect = [member[1] for member in foo_members
if member[0] == "a"][0]
print (id(a_by_getattr), a_by_getattr, type(a_by_getattr))
print (id(a_by_inspect), a_by_inspect, type(a_by_inspect))
# (38842160L, <bound method Foo.method of <__main__.Foo object at 0x00000000025EF390>>, <type 'instancemethod'>)
# (39673576L, <bound method Foo.method of <__main__.Foo object at 0x00000000025EF390>>, <type 'instancemethod'>)
# (34072832L, 100, <type 'int'>)
# (34072832L, 100, <type 'int'>)
对于“a”属性,getattr 和 inspect.getmembers 返回相同的对象。但是对于“方法”方法,它们返回不同的对象(从不同的 id 可以看出)。
为什么会这样?