Self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in Python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.
What is the use of self in Python?
When working with classes in Python, the term “self” refers to the instance of the class that is currently being used. It is customary to use “self” as the first parameter in instance methods of a class. Whenever you call a method of an object created from a class, the object is automatically passed as the first argument using the “self” parameter. This enables you to modify the object’s properties and execute tasks unique to that particular instance.
Python
class Mynumber:
def __init__(self, value):
self.value = value
def print_value(self):
print(self.value)
obj1 = Mynumber(17)
obj1.print_value()
Output:
17
Python Class self Constructor
When working with classes, it’s important to understand that in Python, a class constructor is a special method named __init__ that gets called when you create an instance (object) of a class. This method is used to initialize the attributes of the object. Keep in mind that the self parameter in the constructor refers to the instance being created and allows you to access and set its attributes. By following these guidelines, you can create powerful and efficient classes in Python.
Python
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
Is self in Python a Keyword?
No, ‘ self ‘ is not a keyword in Python. Self is just a parameter name used in instance methods to refer to the instance itself.
In a more clear way you can say that SELF has the following Characteristic-
Self: Pointer to Current Object
The self is always pointing to the Current Object. When you create an instance of a class, you’re essentially creating an object with its own set of attributes and methods.
Python
class Check:
def __init__(self):
print("Address of self = ",id(self))
obj = Check()
print("Address of class object = ",id(obj))
Output:
Address of self = 140273244381008
Address of class object = 140273244381008
Example: Creating Class with Attributes and Methods
This code defines a Python class car representing cars with attributes ‘model’ and ‘color’. The __init__ constructor initializes these attributes for each instance. The show method displays model and color, while direct attribute access and method calls demonstrate instance-specific data retrieval.
Python
class Car():
# init method or constructor
def __init__(self, model, color):
self.model = model
self.color = color
def show(self):
print("Model is", self.model )
print("color is", self.color )
# both objects have different self which contain their attributes
audi = Car("audi a4", "blue")
ferrari = Car("ferrari 488", "green")
audi.show() # same output as car.show(audi)
ferrari.show() # same output as car.show(ferrari)
print("Model for audi is ",audi.model)
print("Colour for ferrari is ",ferrari.color)
Output:
Model is audi a4
color is blue
Model is ferrari 488
color is green
Model for audi is audi a4
Colour for ferrari is green
Self in Constructors and Methods
Self is the first argument to be passed in Constructor and Instance Method.Self must be provided as a First parameter to the Instance method and constructor. If you don’t provide it, it will cause an error.
Python
# Self is always required as the first argument
class Check:
def __init__():
print("This is Constructor")
object = Check()
print("Worked fine")
# Following Error is produced if Self is not passed as an argument
Traceback (most recent call last):
File "/home/c736b5fad311dd1eb3cd2e280260e7dd.py", line 6, in <module>
object = Check()
TypeError: __init__() takes 0 positional arguments but 1 was given
Self: Convention, Not Keyword
Self is a convention and not a Python keyword. Self is a parameter in Instance Method and the user can use another parameter name in place of it. But it is advisable to use self because it increases the readability of code, and it is also a good programming practice.
Python
class This_is_class:
def __init__(in_place_of_self):
print("we have used another "
"parameter name in place of self")
object = This_is_class()
Output:
we have used another parameter name in place of self
self in Python class – FAQs
What is the self Keyword in Python Classes?
The self keyword in Python is used to represent an instance (object) of a class. It allows you to access attributes and methods of the class in Python. It must be the first parameter of any method in the class, including the __init__ method, which is the constructor.
How to Use self to Access Instance Attributes in Python Classes?
You use self to access instance attributes and methods within a class. When you define instance attributes in the __init__ method or any other method, you use self.attribute_name to refer to them.
Example:
class Person:
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age # instance attribute
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Creating an instance of the Person class
person = Person("Alice", 30)
person.display_info() # Output: Name: Alice, Age: 30
What is the Role of self in Python Methods?
The role of self in Python methods is to refer to the instance calling the method. It is how the method accesses the instance’s attributes and other methods. Without self, the method would not know which instance’s attributes to use.
Example:
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
# Creating an instance of the Circle class
circle = Circle(5)
print(circle.area()) # Output: 78.5
In this example, the area method uses self.radius to calculate the area of the circle instance.
How to Create Methods that Modify Class State in Python Using self?
To create methods that modify the state of a class, you use self to refer to and update instance attributes.
Example:
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
# Creating an instance of the Counter class
counter = Counter()
counter.increment()
counter.increment()
counter.decrement()
print(counter.get_count()) # Output: 1
In this example, the increment and decrement methods modify the count attribute of the Counter instance.
Is it Mandatory to Write self in Python?
Yes, it is mandatory to write self as the first parameter in instance methods of a class in Python. While the name self is a convention, it is not a keyword, and you can technically use any name, but it must be the first parameter of the method. Using self is a widely accepted convention and improves code readability.
Example:
class Example:
def method(self):
print("This method belongs to the instance")
# Creating an instance of the Example class
example = Example()
example.method() # Output: This method belongs to the instance