python - 如何检查一个变量是否是一个属性

标签 python python-3.x properties

<分区>

假设有一个定义了@property的类:

class MyClass:
   ...
   @property
   def this_is_a_property(self):
       return self.some_thing
   ...
   def this_is_a_function(self, x):
       ...
       return other_thing

通常,要检查属性是否为函数,我可以使用 inspect 模块中的 isfunction

 import inspect
 if inspect.isfunction(MyClass.__dict__['this_is_a_function']):
    print('this_is_a_function',' is a function')

如何检查属性?似乎没有 inspect.isproperty 函数。

最佳答案

只需根据 property 对象检查类型:

if isinstance(MyClass.this_is_a_property, property):

你真的不必在这里从类字典中检索它;在类上查找属性作为属性也会返回 property 实例。

关于python - 如何检查一个变量是否是一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29460728/

相关文章:

python - 在 Python 中将嵌套字典位置作为参数传递

带有可变十进制数说明符的 Python f 字符串

python - 如何在子类中使用描述符的装饰器

javascript - JS。原型(prototype)奇怪行为中的属性

python - 我将如何覆盖 django rest 框架中的 perform_destroy 方法?

递归函数中的 Python 生成器

python - 根据键修剪有序字典?

python - Matplotlib 'key_press_event' 没有响应

excel - 获取 Excel 名称管理器定义的特定单元格的 'Name'

java - 属性文件位置java