【问题标题】:get source code for method with @property decorator python使用 @property 装饰器 python 获取方法的源代码
【发布时间】:2018-04-04 12:10:30
【问题描述】:

假设我有一个 MyClass 类,它有一个使用 @property 装饰器创建的属性,如下所示:

class MyClass(object):
    @property
    def foo(self):
        if whatever:
            return True
        else:
            return False

假设我想使用 python 检查模块来获取定义属性的源代码。我知道如何为方法(inspect.getsource)执行此操作,但我不知道如何为属性对象执行此操作。有人知道怎么做吗?

【问题讨论】:

  • 嗯。我很惊讶inspect.getsource 不能自动处理。
  • 作为一项新功能可能值得提出要求

标签: python introspection inspect


【解决方案1】:

通过属性的fget属性访问底层getter函数:

print(inspect.getsource(MyClass.foo.fget))

如果它有设置器或删除器,您可以通过fsetfdel 访问它们:

print(inspect.getsource(MyClass.foo.fset))
print(inspect.getsource(MyClass.foo.fdel))

【讨论】:

  • 太棒了!正是我需要的!
猜你喜欢
  • 2016-04-02
  • 2021-11-27
  • 2022-01-18
  • 1970-01-01
  • 2017-01-25
  • 2019-12-21
  • 2016-03-14
相关资源
最近更新 更多