如何在 python 中获取 属性 的名称

How to get the name of a property in python

如何在 python 中获取 属性 的名称?欢迎任何建议。

对于函数和方法,它就像f.__name__一样简单。

但是属性没有 __name__ 属性。

属性 没有名称,但您可能真的在寻找其 fget 属性的名称,该名称(忽略事后所做的任何改组)将是property 实例绑定到的 class 属性。

class A:
    @property
    def foo(self):
        return 3


assert A.foo.fget.__name__ == "foo"

如果您知道父级 class、dir()vars(),并且主要是 __dict__() 就是您要查找的内容。如果你只有属性本身,在 class 的上下文之外,那么我相信你不能。