简体   繁体   English

有没有办法检查一个属性是否有一个setter?

[英]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 :以下是我认为没有成功的两种途径:

  1. Using hasattr to find if a method named my_property.setter or something like that exists.使用hasattr查找名为my_property.setter或类似方法的方法是否存在。
  2. Using the 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.

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