Determine if given class attribute is a property or not, Python object

后端 未结 3 957
臣服心动
臣服心动 2020-12-14 00:58

It\'s all in the title. Here is the following example:

class A(object):
    my_var = 5

    def my_method(self, drink=\'beer\'):
        return \'I like %s\'         


        
3条回答
  •  猫巷女王i
    2020-12-14 01:24

    You need to look at the class (this is the case for descriptors in general), which for objects you can find via the __class__ attribute or by using the type function:

    >>> obj.__class__.my_property
    
    

    or by

    >>> type(obj).my_property
    
    

    These result in the same "property object" as if you were to directly check the attribute of the class (implying you know the class' name in your code instead of checking it dynamically like you probably should rather do):

    >>> A.my_property
    
    

    So to test if a specific attribute of an object is a property, this would be one solution:

    >>> isinstance(type(obj).my_property, property)
    True
    

提交回复
热议问题