Python ProgrammingPython Programming

How to Iterate over object attributes in Python?

Calling dir on the object gives you back all the attributes of that object, including python special attributes.You can always filter out the special methods by using a list comprehension.
class A():
    m = 1
    n = 2
 
    def __int__(self, x=1, y=2, z=3):
        self.x = x
        self._y = y
        self.__z__ = z
 
    def xyz(self):
        print(x, y, z)
 
 
obj = A()
print(dir(obj))
print([a for a in dir(obj) if not a.startswith('__')])
Sample output of above program.
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'm', 'n', 'xyz']
['m', 'n', 'xyz']