Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get properties of object in python [duplicate]

class ClassB:
    def __init__(self):
        self.b = "b"
        self.__b = "__b"

    @property
    def propertyB(self):
        return "B"

I know getattr,hasattr... can access the property. But why don't have the iterattr or listattr?

Expect result of ClassB object:

{'propertyB': 'B'}

Expect result of ClassB class:

['propertyB']

Thanks @juanpa.arrivillaga 's comment. vars(obj) and vars(obj.__class__) is different!

like image 803
JustWe Avatar asked Sep 07 '25 15:09

JustWe


1 Answers

Use the built-in vars as follows:

properties = []
for k,v in vars(ClassB).items():
    if type(v) is property:
        properties.append(k)

Using a list-comprehension:

>>> [k for k,v in vars(ClassB).items() if type(v) is property]
['propertyB']
like image 124
lmiguelvargasf Avatar answered Sep 09 '25 03:09

lmiguelvargasf