Published Aug. 3, 2023, 1:25 p.m.
In Python, the self
variable is a default reference that always points to the current object (similar to the this
keyword in Java). It allows us to access instance variables and instance methods of the object. The self
variable should always be the first parameter inside the constructor (__init__(self)
) and instance methods (def talk(self):
).
self
VariableLet's create a simple class called Person
to demonstrate the usage of the self
variable.
class Person:
def __init__(self, name, age):
# Constructor with `self` as the first parameter
self.name = name
self.age = age
def talk(self, message):
# Method with `self` as the first parameter
return f"{self.name} says: {message}"
Now, let's create an instance of the Person
class and use the self
variable to access instance variables and call instance methods.
# Create an instance of the Person class
person1 = Person("Alice", 30)
# Access instance variables using `self`
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
# Call instance method using `self`
message = person1.talk("Hello, nice to meet you!")
print(message) # Output: Alice says: Hello, nice to meet you!
We define a class Person
with a constructor (__init__
) that takes three parameters: self
, name
, and age
. The self
parameter is mandatory and represents the instance of the class.
Inside the constructor, we use the self
variable to initialize the instance variables name
and age
with the values provided as arguments during object creation.
We define an instance method talk()
that also takes self
as the first parameter, along with an additional parameter message
. The self
parameter is necessary to access the instance variables and other methods of the object.
We create an instance of the Person
class called person1
with the name "Alice" and age 30.
We use the self
variable to access the instance variables name
and age
of person1
using dot notation (person1.name
, person1.age
).
We call the talk()
method on person1
using the self
variable, passing the message "Hello, nice to meet you!". The method uses self.name
to retrieve the name of the person and combines it with the provided message to generate the output.
The self
variable is crucial in Python classes as it allows us to work with specific instance data, making it possible to create multiple objects with different attributes and behaviors within the same class blueprint.