Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to print all object properties in one line [duplicate]

Tags:

python

How to print all object properties in one like something like:

print obj

but this does not print all properties of the object

like image 804
Blurry Script Avatar asked Jan 19 '18 09:01

Blurry Script


People also ask

How do you print all the properties of an object in Python?

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.

What is __ str __ in Python?

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.

How do you print all objects in a class Python?

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.


2 Answers

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

like image 147
Harsha Biyani Avatar answered Oct 12 '22 09:10

Harsha Biyani


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))
like image 28
Gwendal Grelier Avatar answered Oct 12 '22 10:10

Gwendal Grelier