Video Tutorials Like the constructors in Java, the init method is a special method that gets called whenever a new object is created or instantiated. Its full name is __init__ (two underscore characters, followed by keyword init, and followed by two more underscores).
Let us take an example to understand the __init__ method. An init method for the Time class might look like this. The time class
has three attributes Hour, Minute, and Second. As and when a new object of the Time class is created these three attributes are initialized. The different possible cases are shown below. It is common for the parameters of __init__ to have the same names as the attributes. The statement self.hour = hour stores the value of the parameter hour as an attribute of the self. As shown in the output, if you create a new
object with no parameters, attributes Hour, Minute and Second are initialized to 0 and so on. like __init__ method, __str__ is also a special method, that returns a string representation of an object. For example, here is an str method for Time objects. As and when the print function is called with primitive data like string, number, etc the values are printed normally. But when the print is called with object as the
parameters, the __str__ function is called. The __str__ function returns the string form of the result. Finally, the print function displays the result. If you like the tutorial share it with your friends. If you want to get
the regular update regarding VTU CBCS notes, question papers, Interview preparation like our Facebook page.The init method
Video Tutorial
The init method for Time class
class Time:
"""Represents the time of day. attributes: hour, minute, second"""
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def print_time(t):
print('Hour:', t.hour, '\nMinute: ', t.minute, '\nSeconds: ', t.second)
#The parameters are optional, so if you call Time with no arguments, you get the default
values.
print('----------------')
time1 = Time()
time1.print_time()
#If you provide one argument, it overrides hour:
print('----------------')
time2 = Time(10)
time2.print_time()
#If you provide two arguments, they override hour and minute.
print('----------------')
time3 = Time(10,20)
time3.print_time()
#If you provide two arguments, they override hour, minute and seconds
print('----------------')
time4 = Time(10,20,30)
time4.print_time() Output:
----------------
Hour: 0
Minute: 0
Seconds: 0
----------------
Hour: 10
Minute: 0
Seconds: 0
----------------
Hour: 10
Minute: 20
Seconds: 0
----------------
Hour: 10
Minute: 20
Seconds: 30 The __str__ method
Output:
----------------
00:00:00
----------------
10:20:00
----------------
10:20:40 Clik here to read Solution to Python Application Programming Question Paper Jan 2019 15CS664
Shahpar Khan
The need for __str__ method:
The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.
The __str__ method is called when the following functions are invoked on the object and return a string:
- print()
- str()
If we have not defined the __str__, then it will call the __repr__ method. The __repr__ method returns a string that describes the pointer of the object by default (if the programmer does not define it).
How to call __str__ method
1. Default implementation
class MyClass:
x = 0
y = ""
def __init__(self, anyNumber, anyString):
self.x = anyNumber
self.y = anyString
myObject = MyClass(12345, "Hello")
print(myObject.__str__())
print(myObject.__repr__())
print(myObject)
The above code shows an example where neither __str__ nor __repr__ are defined. Calling __str__ calls the default __repr__ method, and they all give the same output, the pointer of our object.
2. Custom __str__ method
class MyClass:
x = 0
y = ""
def __init__(self, anyNumber, anyString):
self.x = anyNumber
self.y = anyString
def __str__ (self):
return 'MyClass(x=' + str(self.x) + ' ,y=' + self.y + ')'
myObject = MyClass(12345, "Hello")
print(myObject.__str__())
print(myObject)
print(str(myObject))
print(myObject.__repr__())
The code above shows the output once you have defined the __str__ method. When __str__, print(), or str() are called you will get your defined output. Make note that the __repr__ output remains the same.
3. __repr__ method defined only
class MyClass:
x = 0
y = ""
def __init__(self, anyNumber, anyString):
self.x = anyNumber
self.y = anyString
def __repr__ (self):
return 'MyClass(x=' + str(self.x) + ' ,y=' + self.y + ')'
myObject = MyClass(12345, "Hello")
print(myObject.__str__())
print(myObject)
print(str(myObject))
print(myObject.__repr__())
In the first example we saw that when __str__ is not defined it automatically calls the __repr__ method. Therefore, the output of all the functions - __str__, str(), and __repr__ - are the same. Moreover, the __repr__ method does not necessarily need to return a string. In case it does not return a string, the print() statements will throw an error.
CONTRIBUTOR
Copyright ©2023 Educative, Inc. All rights reserved