Aug-26-2018, 03:21 PM
(This post was last modified: Aug-26-2018, 03:24 PM by Gribouillis.)
(Aug-26-2018, 10:44 AM)NobahdiAtoll Wrote: is there a way to iterate over only properties instead of __dict__ attributesThere are ways of course, I give you a solution below. Before I do that, let me say that it is not a good way to handle your problem because properties are an implementation detail of your code and this should not be mixed with the problem's real world model. I mean that the list of items that you want to output should not be defined by the details of the implementation.
That said, the code below defines a function
add_property_names()
which adds a property_names()
class method to a class and its subclasses. This method allows you to list the names of the class' properties.In your example, you would add the code
add_property_names(videofile)Then you could do
for name in movieitem.property_names(): print(name, getattr(movieitem, name))Here is the code
import inspect def add_property_names(cls): def get_names(cls): for tp in inspect.getmro(cls): for name, value in vars(tp).items(): if isinstance(value, property): yield name def property_names(cls): register = add_property_names.register if not cls in register: register[cls] = sorted(set(get_names(cls))) return register[cls] cls.property_names = classmethod(property_names) return cls add_property_names.register = {} if __name__ == '__main__': class A: pass class B(A): @property def foo(self): return 0 class C(B): @property def bar(self): return self._bar @bar.setter def bar(self, value): self._bar = value add_property_names(A) a = A() print(a.property_names()) c = C() print(c.property_names()) print(C.property_names())