Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object.
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.
To print all instances of a class with Python, we can use the gc module. We have the A class and we create 2 instances of it, which we assigned to a1 and a2 . Then we loop through the objects in memory with gc. get_objects with a for loop.
To print the attributes of an object we can use “object. __dict__” and it return a dictionary of all names and attributes of object. After writing the above code (python print object attributes), once you will print “x. __dict__” then the output will appear.
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()
dir(a)
>>>
['__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.
Maybe you are looking for something like this?
>>> class MyTest:
def __init__ (self):
self.value = 3
>>> myobj = MyTest()
>>> myobj.__dict__
{'value': 3}
try ppretty:
from ppretty import ppretty
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
print ppretty(Animal(), seq_length=10)
Output:
__main__.Animal(age = 10, color = 'Spotted', kids = 0, legs = 2, name = 'Dog', smell = 'Alot')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With