从 Python 类中获取所有 @properties [英] Get all @properties from a Python Class
问题描述
在 Python 中,如何获取一个类的所有 属性,即由 @property
装饰器创建的所有成员?
In Python, how can I get all properties of a class, i.e. all members created by the @property
decorator?
stackoverflow 上至少有两个问题[1, 2] 混淆了术语property 和 attribute,误用了property 作为 attribute 的同义词,在 Python 上下文中会产生误导.因此,即使其他问题的标题可能暗示了这一点,但它们并没有回答我的问题.
There are at least two questions[1, 2] on stackoverflow which confound the terms property and attribute, falsely taking property as a synonym for attribute, which is misleading in Python context. So, even though the other questions' titles might suggest it, they do not answer my question.
[1]:打印 Python 类的所有属性
[2]:是否有内置函数可以打印对象的所有当前属性和值?
推荐答案
我们可以使用 cls.__dict__
获取类 cls
的所有属性代码>.由于property
本身就是某个类,我们可以检查cls
的哪些属性是property
的实例:
We can get all attributes of a class cls
by using cls.__dict__
. Since property
is a certain class itself, we can check which attributes of cls
are an instance of property
:
from typing import List
def properties(cls: type) -> List[str]:
return [
key
for key, value in cls.__dict__.items()
if isinstance(value, property)
]
这篇关于从 Python 类中获取所有 @properties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!