Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Python object, how can I see a list of properties that have been defined with the @property decorator?

I can see first-class member variables using self.__dict__, but I'd like also to see a dictionary of properties, as defined with the @property decorator. How can I do this?

like image 980
Kyle Wild Avatar asked May 03 '11 21:05

Kyle Wild


2 Answers

You could add a function to your class that looks something like this:

def properties(self):
    class_items = self.__class__.__dict__.iteritems()
    return dict((k, getattr(self, k)) 
                for k, v in class_items 
                if isinstance(v, property))

This looks for any properties in the class and then creates a dictionary with an entry for each property with the current instance's value.

like image 99
Andrew Clark Avatar answered Sep 17 '22 13:09

Andrew Clark


The properties are part of the class, not the instance. So you need to look at self.__class__.__dict__ or equivalently vars(type(self))

So the properties would be

[k for k, v in vars(type(self)).items() if isinstance(v, property)]
like image 20
John La Rooy Avatar answered Sep 20 '22 13:09

John La Rooy