oop – Print all properties of a Python Class

oop – Print all properties of a Python Class

In this simple case you can use vars():

an = Animal()
attrs = vars(an)
# {kids: 0, name: Dog, color: Spotted, age: 10, legs: 2, smell: Alot}
# now dump this in some way or another
print(, .join(%s: %s % item for item in attrs.items()))

If you want to store Python objects on the disk you should look at shelve — Python object persistence.

Another way is to call the dir() function (see https://docs.python.org/2/library/functions.html#dir).

a = Animal()
[__class__, __delattr__, __dict__, __doc__, __format__, __getattribute__,
 __hash__, __init__, __module__, __new__, __reduce__, __reduce_ex__, 
 __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, 
 __weakref__, age, color, kids, legs, name, smell]

Note, that dir() tries to reach any attribute that is possible to reach.

Then you can access the attributes e.g. by filtering with double underscores:

attributes = [attr for attr in dir(a) 
              if not attr.startswith(__)]

This is just an example of what is possible to do with dir(), please check the other answers for proper way of doing this.

oop – Print all properties of a Python Class

Maybe you are looking for something like this?

    >>> class MyTest:
        def __init__ (self):
            self.value = 3
    >>> myobj = MyTest()
    >>> myobj.__dict__
    {value: 3}

Leave a Reply

Your email address will not be published. Required fields are marked *