Object methods and the init method
In Python, the __init__()
method is a special method that gets called when an object is created from a class. It is used to initialize the attributes of the object.
Here’s an example of a class with an __init__()
method:
pythonCopy codeclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
In this example, the __init__()
method takes two arguments, name
and age
, and initializes the name
and age
attributes of the object.
To create a new object from this class, we call the class like a function, passing any required arguments:
pythonCopy codep = Person("Alice", 25)
This creates a new Person
object with the name
attribute set to “Alice” and the age
attribute set to 25.
We can then call the object’s methods, like say_hello()
, which can access and operate on the object’s attributes:
pythonCopy codep.say_hello() # prints "Hello, my name is Alice and I'm 25 years old."
In addition to the __init__()
method, we can define other methods on a class that operate on the object’s attributes. These methods take the self
parameter, which refers to the object that the method is being called on.
For example, here’s a class with a have_birthday()
method that increments the age
attribute of the object:
pythonCopy codeclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
def have_birthday(self):
self.age += 1
We can call the have_birthday()
method on a Person
object to increment its age
attribute:
pythonCopy codep = Person("Alice", 25)
p.have_birthday()
p.say_hello() # prints "Hello, my name is Alice and I'm 26 years old."
Overall, the __init__()
method and other methods defined on a class allow us to create and manipulate objects in Python. They are a key part of object-oriented programming in Python.