Mar*_*arc 4 python introspection inspect
假设我有一个 MyClass 类,它有一个使用 @property 装饰器创建的属性,如下所示:
class MyClass(object):
@property
def foo(self):
if whatever:
return True
else:
return False
Run Code Online (Sandbox Code Playgroud)
假设我想使用 python inspect 模块来获取定义属性的源代码。我知道如何为方法 (inspect.getsource) 执行此操作,但我不知道如何为属性对象执行此操作。有人知道怎么做吗?
通过属性的fget属性访问底层的 getter 函数:
print(inspect.getsource(MyClass.foo.fget))
Run Code Online (Sandbox Code Playgroud)
如果它有设置器或删除器,您可以通过fset和访问它们fdel:
print(inspect.getsource(MyClass.foo.fset))
print(inspect.getsource(MyClass.foo.fdel))
Run Code Online (Sandbox Code Playgroud)