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

拥有回忆 提交于 2019-11-29 12:25:54

问题


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?


回答1:


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.




回答2:


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)]



回答3:


For an object f, this gives the list of members that are properties:

[n for n in dir(f) if isinstance(getattr(f.__class__, n), property)]



回答4:


dir(obj) gives a list of all attributes of obj, including methods and attributes.



来源:https://stackoverflow.com/questions/5876049/in-a-python-object-how-can-i-see-a-list-of-properties-that-have-been-defined-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!