2015-04-05 77 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

相關問題