self in Python class
In Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance. It is essential for accessing attributes and methods within the class.
Example:
class Mynumber:
def __init__(self, value):
self.value = value
def print_value(self):
print(self.value)
obj1 = Mynumber(17)
obj1.print_value()
Output
17
What is the Purpose of "self"?
In Python, self is used as the first parameter in instance methods to refer to the current object. It allows methods within the class to access and modify the object's attributes, making each object independent of others.
When we call a method on an object, self automatically gets passed to the method, referring to the specific instance of the class the method is acting upon. Without self, Python wouldn't know which instance’s attributes or methods to refer to.
The Role of "self" in Constructors and Methods
Self in the Constructor (__init__ method)
__init__ method is called when a new instance of the class is created. This method serves as the constructor for the class and initializes the object's attributes. The first argument of the __init__ method must always be self, as it allows the method to set instance attributes for the object being created.
Example:
class Subject:
def __init__(self, attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
obj = Subject('Maths', 'Science')
print(obj.attr1)
print(obj.attr2)
Output
Maths Science
Explanation: In this example, self.attr1 and self.attr2 refer to the attributes of the current object, ensuring that each object can have its own values for these attributes.
Self in Instance Methods
Any method within the class that operates on an instance of the class must include self as the first parameter. It allows us to access the instance's attributes and other methods.
Example:
class Car:
def __init__(self, model, color):
self.model = model
self.color = color
def show(self):
print("Model is", self.model)
print("Color is", self.color)
# Creating instances of the class
audi = Car("Audi A4", "Blue")
ferrari = Car("Ferrari 488", "Green")
# Calling instance methods
audi.show()
ferrari.show()
Output
Model is Audi A4 Color is Blue Model is Ferrari 488 Color is Green
Explanation: In this example, self allows each instance to retain its unique attributes, such as model and color and the show() method displays them.
Is "self" a Keyword?
Although self is not a Python keyword, using it is a widely accepted convention. This makes the code easier to read and understand for other developers, as it follows the general structure of object-oriented programming.
Example:
class Car:
def __init__(this, model, color):
this.model = model
this.color = color
def show(this):
print("Model is", this.model)
print("Color is", this.color)
# using 'this' instead of 'self'
audi = Car("Audi A4", "Blue")
audi.show()
Output
Model is Audi A4 Color is Blue
Explanation: In this case, we use this instead of self. While this works, it's better to stick to the self convention for readability and maintainability of the code.
Self: Pointer to the Current Object
When we create an instance of a class, self points to the current object. It allows us to refer to the instance's attributes and methods. Every object created from a class will have its own self.
Example:
class Check:
def __init__(self):
print("Address of self = ", id(self))
obj = Check()
print("Address of class object = ", id(obj))
Output
Address of self = 140106994493696 Address of class object = 140106994493696
Explanation: Here, self refers to the memory address of the object and we can use id(self) to see its unique memory address.
Creating Methods to Modify Class State Using "self"
Self allows us to modify the internal state of an object, such as updating instance attributes. This is useful when building methods that interact with or modify the object's data.
Example: Modifying the State of an Object
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def decrement(self):
self.count -= 1
def get_count(self):
return self.count
# using the Counter class
counter = Counter()
counter.increment()
counter.increment()
counter.decrement()
print(counter.get_count())
Output
1
Explanation: In this example, self.count keeps track of the counter's state and the methods increment, decrement and get_count modify or access the count.