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:
Python
class Mynumber:
def __init__(self, value):
self.value = value
def print_value(self):
print(self.value)
obj1 = Mynumber(17)
obj1.print_value()
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:
Python
class Subject:
def __init__(self, attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
obj = Subject('Maths', 'Science')
print(obj.attr1)
print(obj.attr2)
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.
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:
Python
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()
OutputModel 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:
Python
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()
OutputModel 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:
Python
class Check:
def __init__(self):
print("Address of self = ", id(self))
obj = Check()
print("Address of class object = ", id(obj))
OutputAddress 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
Python
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())
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.
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?
We 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
Similar Reads
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
6 min read
Python objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Class and Object
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 cla
6 min read
Class and Instance Attributes in Python
Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self):
2 min read
Create a Python Subclass
In Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in Python
Python is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword. Example of class [GFGTABS] P
5 min read
Python MetaClasses
The key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in Python
In Python, an instance object is an instantiation of a class, and it is a unique occurrence of that class. Creating instance objects is a fundamental concept in object-oriented programming (OOP) and allows developers to work with and manipulate specific instances of a class. This article will explor
3 min read
Dynamic Attributes in Python
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in Python
In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default Argument
In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure. Example: [GFGTABS] Python class Car: def __init__(self, brand, model): self.brand = brand # Set instanc
3 min read
Encapsulation and Access Modifiers
Encapsulation in Python
In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
6 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of
6 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Method Overriding in Python
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
9 min read
Python super()
In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class. Syntax of super() in PythonSyntax: super() Return : R
8 min read
Multiple Inheritance in Python
Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
5 min read
What Is Hybrid Inheritance In Python?
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Special Methods and Testing