In Python, self
is a conventional name used to refer to the instance of a class within the class’s methods. It allows accessing the attributes and methods of the current object. When defining a class method, the first parameter is typically named self
(although you can choose a different name), and it represents the instance on which the method is called.
Here’s an example to illustrate the use of self
in Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
def celebrate_birthday(self):
self.age += 1
print(f"Happy birthday! Now I am {self.age} years old.")
# Creating an instance of the Person class
john = Person("John", 25)
# Accessing attributes using 'self'
print(john.name) # Output: John
print(john.age) # Output: 25
# Calling methods using 'self'
john.introduce() # Output: My name is John and I am 25 years old.
john.celebrate_birthday() # Output: Happy birthday! Now I am 26 years old.
Code language: Python (python)
In the example above, the self
parameter is used to access and modify the name
and age
attributes of the Person
instance (john
). The self.introduce()
method uses self.name
and self.age
to introduce the person. Similarly, the self.celebrate_birthday()
method increments the person’s age by 1 using self.age
.
By convention, the self
parameter is used within class methods, but it is not required to use the name self
. However, it is recommended to use it as it improves code readability and makes it easier to understand the purpose of the parameter.
Read More;
- Simple Python Script Example [Super Simple!]
- K-means Clustering for Anomaly Detection
- What is f’ Python [With Examples]
- Is Python Similar to R [Easier Than Python?]
- Best Python Library to Detect Language
- How do I write a YAML file in Python?
- What is Statement in Python With Example?
- What Does ‘w’ Do in Python [With Examples]
- The Programming Cycle for Python With Example
- How to Use f.write in Python? [Write in a Text File]
- What is Token in Python With Example
- List I j in Python [Detailed Examples]