JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Printing objects of a class in Python

Author:JIYIK Last Updated:2025/05/06 Views:

In this tutorial, we will look at various ways to print class objects in Python. Suppose we want to print()print a class instance using the print("print") function, for example to see the data or value of an object. We can do this using the methods described below.


__repr__()Printing an object using the method in Python

__repr__()The method returns a printable representation of the object as a string. By default, it returns the name of the object's class and the object's address.

When we print()print an object in Python using print() function, the print( __str__()) method of the object is called. If it is not defined, then print() returns the return value of the print() method. That is why when we try to print an object of a user defined class using print() function, it returns the return value of the print() method.__str__()__repr__()print()__repr__()

Therefore, we can define or override __repr__()the method to print the summary or required value of an object.

Suppose we have a user defined class ClassAwhich has no __repr__()method. The following sample code demonstrates the output when we try to print an object __repr__()which has no method ClassA.

class classA:
    def __init__(self):
        self.var1 = 0
        self.var2 = "Hello"


A = classA()
print(A)

Output:

<__main__.classA object at 0x7fa29aa28c50>

Since we haven't defined __repr__()the method, by default it returns the name of the class and the address of the object.

Now, let's define the method classAof the class __repr__()and then use print()the function. print()and print(repr())should return the same value.

class classA:
    def __init__(self):
        self.var1 = 0
        self.var2 = "Hello"

    def __repr__(self):
        return "This is object of class A"


A = classA()
print(A)
print(repr(A))

Output:

This is object of class A
This is object of class A

__str__()Printing an object using the method in Python

__str__()The method returns a string version of the object in Python. If the object does not have __str__()a method, it returns __repr__()the same value as the method.

We see in the example code above that if __str__()the method is not defined, the print()method will use __repr__()the method to print a printable representation of the object.

Now, let's define the method ClassAof our example class __str__()and then try to print()print classAan object of using the function. print()The function should return __str__()the output of the method.

class classA:
    def __init__(self):
        self.var1 = 0
        self.var2 = "Hello"

    def __repr__(self):
        return "This is object of class A"

    def __str__(self):
        print("var1 =", self.var1)
        print("var2 =", end=" ")
        return self.var2


A = classA()
print(A)

Output:

var1 = 0
var2 = Hello

Printing objects in Python by adding new class methods

We can use another method to replace or define the __str__()and __repr__()methods of a class. We can describe a new print() method in a class which will print out the class attributes or values ​​of our choice.

The following example code demonstrates how to define and then use object.print()the method to print an object in Python.

class classA:
    def __init__(self):
        self.var1 = 0
        self.var2 = True
        self.var3 = "Hello"

    def print(self):
        print("var1 =", self.var1)
        print("var2 =", self.var2)
        print("var3 =", self.var3)


A = classA()
A.var2 = False
A.print()

Output:

var1 = 0
var2 = False
var3 = Hello

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Writing logs to a file in Python

Publish Date:2025/05/06 Views:132 Category:Python

This tutorial will show you how to write logs to files in Python. Use the module in Python logging to write logs to files Logging is used to debug a program and find out what went wrong. logging The log module is used to log data to a file

Comparing two dates in Python

Publish Date:2025/05/06 Views:97 Category:Python

This tutorial explains how to compare two dates in Python. There are multiple ways to determine which date is greater, so the tutorial also lists different sample codes to illustrate the different methods. Comparing two dates in Python usin

Reload or unimport modules in Python

Publish Date:2025/05/06 Views:58 Category:Python

Modules allow us to store definitions of different functions and classes in Python files, which can then be used in other files. pandas , NumPy , scipy , Matplotlib are the most widely used modules in Python. We can also create our own modu

Pausing program execution in Python

Publish Date:2025/05/06 Views:156 Category:Python

This tutorial will demonstrate various ways to pause a program in Python. Pausing the execution of a program or application is used in different scenarios, such as when a program requires user input. We may also need to pause the program fo

Importing modules from a subdirectory in Python

Publish Date:2025/05/06 Views:190 Category:Python

This tutorial will explain various ways to import modules from subdirectories in Python. Suppose we have a file in a subdirectory of our project directory and we want to import this file and use its methods in our code. We can import files

Sleeping for a number of milliseconds in Python

Publish Date:2025/05/06 Views:124 Category:Python

In this tutorial, we will look at various ways to pause or suspend the execution of a program in Python for a given amount of time. Let's say we want to pause the execution of a program for a few seconds to let the user read instructions ab

Python Numpy.pad Function

Publish Date:2025/05/06 Views:104 Category:Python

In Python, we have NumPy the array module to create and use arrays. Arrays can have different sizes and dimensions. Padding is a useful method that can be used to compensate for the size of an array. We can mutate an array and add some padd

Generating Random Colors in Python

Publish Date:2025/05/06 Views:135 Category:Python

In the digital world, colors are represented in different formats. RGB, Hexadecimal format are just some of the commonly used formats. In this tutorial, we will learn how to generate random colors in Python. When we talk about generating ra

Getting the name of a class in Python

Publish Date:2025/05/06 Views:83 Category:Python

Just like object constructors, classes can be defined as user-defined prototypes for creating objects. class Classes can be created using the keyword . A class is a data structure that can contain both data members and member methods. This

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial