【发布时间】:2021-02-05 07:39:05
【问题描述】:
在 Python 3.X 中有没有办法检查一个类是否为其属性之一定义了 setter 方法?
假设我有以下示例:
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
我可以检查my_property 是否用hasattr 定义,但我找不到检查setter 是否已定义的方法。
以下是我考虑过但没有成功的两种途径:
- 使用
hasattr查找名为my_property.setter或类似名称的方法是否存在。 - 使用
inspect.signature函数查看my_property方法是否有2个参数(self和new_value)。
我想这个问题的扩展答案也会考虑如何检测 getter 的存在(区分属性和 getter 方法,因为 callable(test.my_property) 在我们认为应该是时返回 False True 因为它是一种方法)。
【问题讨论】:
-
如果属性不是
property怎么办?可以设置它,但它没有setter。在这种情况下,您希望检查是肯定的(就好像它有一个 setter)还是否定的? -
相关:stackoverflow.com/questions/17330160/…(几乎是重复的,因为答案在接受的某处......)
-
“当我们认为它应该是 True 因为它是一种方法时)。” – 不,
test.my_property既不是方法也不是属性。Test.my_property是。
标签: python python-3.x setter