如何检查变量是否属性

uda*_*day 4 python properties python-3.x

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

class MyClass:
   ...
   @property
   def this_is_a_property(self):
       return self.some_thing
   ...
   def this_is_a_function(self, x):
       ...
       return other_thing
Run Code Online (Sandbox Code Playgroud)

通常,要检查属性是否是函数,我可以isfunctioninspect模块中使用.

 import inspect
 if inspect.isfunction(MyClass.__dict__['this_is_a_function']):
    print('this_is_a_function',' is a function')
Run Code Online (Sandbox Code Playgroud)

我该property怎么检查?似乎没有任何inspect.isproperty功能.

Mar*_*ers 7

只需检查property对象的类型:

if isinstance(MyClass.this_is_a_property, property):
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,虽然这不是一种测试方法; 实际的实例可能是*另一个*描述符,只在查找一个类时返回一个`property`;)(牵强是的) (3认同)