The __init__()
method is known as a constructor in object-oriented programming (OOP) terminology. It is used to initialize an object’s state when it is created. This method is automatically called when a new instance of a class is instantiated.
Purpose:
- Assign values to object properties.
- Perform any initialization operations.
Example:
We have created a book_shop
class and added the constructor and book()
function. The constructor will store the book title name and the book()
function will print the book name.
To test our code we have initialized the b
object with “Sandman” and executed the book()
function.
class book_shop:
# constructor
def __init__(self, title):
self.title = title
# Sample method
def book(self):
print('The tile of the book is', self.title)
b = book_shop('Sandman')
b.book()
# The tile of the book is Sandman
Leave a Reply