Print Python objects can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need detailed information for debugging while __str__
is used to print a string version for the users. Printing objects give us information about the objects we are working with
Print Python object example
Simple example code to demonstrate object printing.
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:% s b:% s" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is % s, " \
"b is % s" % (self.a, self.b)
# Driver Code
t = Test(1000, 5544)
# This calls __str__()
print(t)
# This calls __repr__()
print([t])
Output:
Print object/instance name in Python
class badguy(object):
def __init__(self):
pass
b = badguy()
print(b)
Output: <main.badguy object at 0x0000022291762650>
How to print() an object in a list in Python
class Student:
def __init__(self, std_id, std_name, std_dob, std_mark=0):
self.student_id = std_id
self.student_name = std_name
self.student_dob = std_dob
self.student_mark = std_mark
def __repr__(self):
return (
f"ID: {self.student_id}\n"
f"Name: {self.student_name}\n"
f"Dob: {self.student_dob}\n"
f"GPA: {self.student_mark}\n"
)
def list_student(self, student):
print("ID: ", student.student_id)
print("Name: ", student.student_name)
print("Dob: ", student.student_dob)
print("GPA: ", student.student_mark)
print("\n")
exmStudent = Student(1234, "John", "Std_dob", -20)
print(exmStudent)
Output:
ID: 1234
Name: John
Dob: Std_dob
GPA: -20
Do comment if you have any doubts or suggestions on this Python Print topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.