检查类属性是否有 setter [英] Check if class property has a setter
问题描述
我需要列出一个类的所有属性,这些属性是属性并且有一个 setter.例如这个类:
class MyClass(object):def __init__(self):自己.一 = 1self._b = 2self._c = 3@财产定义 b(自我):返回 self._b@财产def c(self):返回 self._c@c.setterdef c(self, value):self._c = 值
我需要获取属性 c 而不是 a 和 b.使用此答案:https://stackoverflow.com/a/5876258/7529716我可以得到属性对象 b 和 c.
但这是他们知道这些属性是否有除尝试之外的 setter 的一种方式:
inst = MyClass()尝试:上一个 = inst.binst.b = 无除了属性错误:pass # 没有 setter最后:inst.b = 上一个
提前致谢.
property
对象 将它们的getter、setter 和deleter 分别存储在fget
、fset
和fdel
属性中.如果属性没有设置器或删除器,则该属性设置为 None
.
这意味着您可以简单地过滤掉那些 fset
属性设置为 None
的属性:
def get_writeable_properties(cls):返回 [attr 的属性,vars(cls).items() 中的值如果 isinstance(value, property) 和 value.fset 不是 None]
<预><代码>>>>get_writeable_properties(MyClass)['C']
I need to list all the attribute of a class that are properties and have a 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. Using this answers: https://stackoverflow.com/a/5876258/7529716 i can get the property object b and c.
But is their a way to know if those properties have a setter other than trying:
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. If a property doesn't have a setter or deleter, the attribute is set to None
.
This means you can simply filter out those properties whose fset
attribute is set to 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']
这篇关于检查类属性是否有 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!