2015-04-05 78 views
2

假设有一个与所定义的@property一类:如何检查一个变量是一个属性

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

通常,检查属性是否是一个函数,我可以使用isfunctioninspect模块。

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

我如何检查property?似乎没有inspect.isproperty函数。

回答

4

简单地检查对property对象类型:

if isinstance(MyClass.this_is_a_property, property): 

你真的没有从类字典这里检索;在类上查找属性也会返回property实例。

+3

肯定的,虽然这不是一定的方式来测试此;实际的实例可能是*另一个*描述符,当在一个类上查找时,它只返回一个'property';)(很远是的) – 2015-04-05 19:48:50

3

你可以使用inspect.isdatadescriptor

返回true,如果对象是一个数据描述符。 ...例子是 属性(在Python中定义),getset和成员。

...

CPython的实现细节: getsets是经由PyGetSetDef结构在扩展模块中定义的属性。

...

CPython的实现细节:成员描述符是通过PyMemberDef结构扩展模块定义的属性

数据的描述都只是有一定的方法类型。见3.3.2.1. Implementing Descriptors

如果描述符定义__set__()和/或__delete__(),它是一个数据 描述符;如果它既不定义,它也是一个非数据描述符。

非数据描述符包括classmethodstaticmethod(也就是说,他们没有功能,它们是类型)。例如,inspect.isdatadescriptor(MyClass.this_is_a_classmethod)将返回False

在另一方面,property一个数据描述符:

In [6]: inspect.isdatadescriptor(MyClass.this_is_a_property) 
Out[6]: True 

在使用该功能的缺点是,它可能会返回True如果isinstance(mystery, property)False

一种更好的方式是检查对象直接类型:

In [7]: isinstance(MyClass.this_is_a_property, property) 
Out[7]: True 
+1

'property'是一个*类型的数据描述符;任何具有'__get__'和'__set__'方法的对象都有资格;这包括用'__slots__'定义的属性。 – 2015-04-05 21:34:56

+0

@MartijnPieters谢谢,我更新了我的答案。 – vaultah 2015-08-30 13:21:16

相关问题