简体   繁体   English

检查类属性是否有 setter

[英]Check if class property has a setter

I need to list all the attribute of a class that are properties and have a setter.我需要列出一个类的所有属性,这些属性是属性并且有一个 setter。 For example with this class:例如这个类:

class MyClass(object):
    def __init__(self):
        self. a = 1
        self._b = 2
        self._c = 3

    @property
    def b(self):
        return self._b

    @property
    def c(self):
        return self._c

    @c.setter
    def c(self, value):
        self._c = value

I need to get the attribute c but not a and b.我需要获取属性 c 而不是 a 和 b。 Using this answers: https://stackoverflow.com/a/5876258/7529716 i can get the property object b and c.使用这个答案: https : //stackoverflow.com/a/5876258/7529716我可以获得属性对象 b 和 c。

But is their a way to know if those properties have a setter other than trying:但是他们是一种知道这些属性是否有除尝试之外的 setter 的方法:

inst = MyClass()    
try:
    prev = inst.b
    inst.b = None
except AttributeError:
    pass # No setter
finally:
    inst.b = prev  

Thanks in advance.提前致谢。

property objects store their getter, setter and deleter in the fget , fset and fdel attributes, respectively. property对象分别将它们的 getter、setter 和fset存储在fgetfsetfdel属性中。 If a property doesn't have a setter or deleter, the attribute is set to None .如果属性没有设置器或删除器,则该属性设置为None

This means you can simply filter out those properties whose fset attribute is set to None :这意味着您可以简单地过滤掉fset属性设置为None那些属性:

def get_writeable_properties(cls):
    return [attr for attr, value in vars(cls).items()
                 if isinstance(value, property) and value.fset is not None]
>>> get_writeable_properties(MyClass)
['c']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM