这是交互式 REPL 中的一个示例,将演示如何执行此操作:
>>> class Foo:
... @property
... def bar(self):
... return self
...
>>> f = Foo()
>>> f.bar
<__main__.Foo object at 0x11b197828>
>>> Foo.bar
<property object at 0x11b677548>
>>> f.__class__.__dict__['bar']
<property object at 0x11b677548>
>>> vars(f)
{}
>>> vars(Foo)
mappingproxy({'__module__': '__main__', 'bar': <property object at 0x11b677548>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None})
>>> vars(Foo) == Foo.__dict__
True
>>> type(f) is f.__class__ is Foo
True
>>> {k:v for k, v in vars(Foo).items() if isinstance(v, property)}
{'bar': <property object at 0x11b677548>}
>>> {k:v for k, v in vars(type(f)).items() if isinstance(v, property)}
{'bar': <property object at 0x11b677548>}
>>> dir(Foo)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar']
>>> dir(f)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar']
>>> [d for d in dir(f) if isinstance(getattr(f, d), property)]
[]
>>> [d for d in dir(Foo) if isinstance(getattr(Foo, d), property)]
['bar']