In Python classes, the reserved method init serves a similar purpose as constructors in object-oriented programming (OOP) terminology. When a new object is created, the init method is automatically called, initializing the object and allocating memory for it. This method can also be utilized to set initial values for variables.
Below is an example:
class Human: def __init__(self, age): self.age = age def say(self): print('Hello, my age is', self.age) h = Human(22) h.say()
Output:
Hello, my age is 22
Leave a Reply