[英]Is there a way to check if a property has a setter?
Is there a way in Python 3.X to check if a class defines a setter method for one of its properties? Python 3.X 中有没有办法检查类是否为其属性之一定义了 setter 方法?
Let's say I have the following example :假设我有以下示例:
class Test:
def __init__(self):
self._p = None
@property
def my_property(self):
return self._p
@my_property.setter
def my_property(self, new_value):
self._p = new_value
I can check if my_property
is defined with hasattr
but I can't find a way to check if the setter is defined.我可以检查
my_property
是否用hasattr
定义,但我找不到检查 setter 是否定义的方法。
Here are the two avenues I considered without success :以下是我认为没有成功的两种途径:
hasattr
to find if a method named my_property.setter
or something like that exists.hasattr
查找名为my_property.setter
或类似方法的方法是否存在。inspect.signature
function to see if the method my_property
has 2 parameters (self and new_value).inspect.signature
函数查看方法my_property
是否有2 个参数(self 和new_value)。 I guess that an extended answer to this question would consider how to detect the presence of a getter as well (making the difference between a property and a getter method because callable(test.my_property)
returns False
when we might think it should be True
because it is a method).我想这个问题的扩展答案也会考虑如何检测 getter 的存在(区分属性和 getter 方法,因为
callable(test.my_property)
在我们可能认为它应该是True
时返回False
,因为这是一种方法)。
You can test if the .fset
attribute is None
or not:您可以测试
.fset
属性是否为None
:
>>> Test.my_property.fset is not None # has a setter
True
>>> Test.my_property.fdel is not None # has no deleter
False
The same way you can also test if it has a getter (via .fget
).同样的方式你也可以测试它是否有一个 getter(通过
.fget
)。 To test whether the attribute is a property at all, you can test isinstance(Test.my_property, property)
.要测试该属性是否是一个属性,您可以测试
isinstance(Test.my_property, property)
。
Make sure to always call these on the class level, and not on an individual instance.确保始终在类级别而不是在单个实例上调用这些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.