[英]get source code for method with @property decorator python
Suppose I have a class MyClass that has a property created with the @property decorator, like this: 假设我有一个MyClass类,该类具有使用@property装饰器创建的属性,如下所示:
class MyClass(object):
@property
def foo(self):
if whatever:
return True
else:
return False
Suppose I want to use the python inspect module to get the source code that defines the property. 假设我想使用python inspect模块来获取定义属性的源代码。 I know how to do this for methods (inspect.getsource) but I don't know how to do this for property objects.
我知道如何为方法(inspect.getsource)执行此操作,但我不知道如何为属性对象执行此操作。 Anyone know how to do this?
有人知道怎么做吗?
Access the underlying getter function through the property's fget
attribute: 通过属性的
fget
属性访问基础的getter函数:
print(inspect.getsource(MyClass.foo.fget))
If it has a setter or deleter, you can access those through fset
and fdel
: 如果它具有设置器或删除器,则可以通过
fset
和fdel
访问它们:
print(inspect.getsource(MyClass.foo.fset))
print(inspect.getsource(MyClass.foo.fdel))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.