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

后端 未结 3 959
臣服心动
臣服心动 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条回答
  •  一个人的身影
    2020-12-14 01:26

    I once asked a similar question. The trouble you'll run into, of course, is that you can't access the property through the instance to determine its type without calling the getter, which gets you the type of whatever the getter returns. So you have to access the property through its class rather than through the instance.

    property is already a type, so you can just compare directly to that. (I originally had some superfluous code here that got the property type out of a class that had a property. I thought this was necessary due to a typo when I was testing things.)

    obj_type = type(obj)
    
    for attr in dir(obj):
        if isinstance(getattr(type(obj), attr, None), property):
            print attr, "is a property"
    

    Don't worry about having an instance attribute with the same name. It's ignored in attribute lookup if there's a data descriptor of the same name on the class (property is a data descriptor).

    Of course, any class can be a data descriptor, not just property, so in theory you really want to check for __get__() and/or __set__() and/or __delete__() attributes on the type. But the problem with that approach is that all functions and methods are themselves descriptors and therefore would be caught by that check. It quickly becomes silly to try to find all the exceptions.

提交回复
热议问题