How to print all object properties in one like something like:
print obj
but this does not print all properties of the object
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. Let's say you only wanted to print the object's instance attributes as well as their values, we can use the vars() function.
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.
In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users. Important Points about Printing: Python uses __repr__ method if there is no __str__ method.
you can use builtin method dir(obj)
The default dir()
mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
If the object is a module object, the list contains the names of the module’s attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
source : https://docs.python.org/2/library/functions.html#dir
You can add build-in function to your object (e.g __str__(
) or __repr__()
)
class MyObject:
def __init__(self):
#add proprieties
self.x = 32
self.y = 43
def __str__(self):
return ("Object: " + str(self.x) + " " + str(self.y))
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