Skip to main content
 首页 » 编程设计

python之如何获得所有装饰有 `@property` 的方法的列表

2025年05月04日11zhengyun_ustc

如何获取一个类中所有被@property装饰器装饰过的方法的列表?

在下面的示例中,答案应该得到一个仅包含 x 和 y 的列表,但不包含 z,因为它没有没有用 @property 装饰:

class C(object): 
    def __init__(self): 
        self._x = None 
        self._y = None 
 
    @property 
    def x(self): 
        """I'm the 'x' property.""" 
        return self._x 
 
    @x.setter 
    def x(self, value): 
        self._x = value 
 
    @x.deleter 
    def x(self): 
        del self._x 
 
    @property 
    def y(self): 
        return self._y 
 
    def z(self): 
        pass 

请您参考如下方法:

被@property修饰的方法是property的实例:

>>> [name for name in dir(C) if isinstance(getattr(C, name), property)] 
['x', 'y']