The Wayback Machine - https://web.archive.org/web/20241004041848/https://www.geeksforgeeks.org/self-in-python-class/
Open In App

self in Python class

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Previous Article
Next Article

Similar Reads

Python Library for Self-Balancing BST
Here we will see simulating the library framework TreeSet which is available in Java on Python. There are situations that arise to disallow duplicate entries especially in any management software where an object is uniquely identified by its uniqueness. In this post, let us see how to do that in Pythonic way. In our implementation, "TreeSet" class
4 min read
Self Type in Python
Self-type is a brand-new function added to Python 3.11. A method or function that returns an instance of the class it belongs to is defined by the self type. In situations where we wish to enforce that a method returns an instance of the class and not some other type, self-type is beneficial. Returning an instance of the class in PythonIn this exam
2 min read
Nameerror: name self is not defined in Python
Python, a dynamically typed and object-oriented programming language, is lauded for its simplicity and readability. However, even the most seasoned developers can encounter stumbling blocks, and one such common hurdle is the "NameError: name 'self' is not defined." In this article, we will see how to fix Nameerror: Name 'self' is not defined in Pyt
4 min read
Why Python Uses 'Self' as Default Argument
Python, a versatile and widely used programming language, follows object-oriented principles in its design. One of the distinctive features of Python is the use of the keyword 'self' as a default argument in class methods. This choice plays a crucial role in maintaining the integrity of object-oriented programming (OOP) concepts and ensures proper
3 min read
Self Organizing Maps - Kohonen Maps
Self Organizing Map (or Kohonen Map or SOM) is a type of Artificial Neural Network which is also inspired by biological models of neural systems from the 1970s. It follows an unsupervised learning approach and trained its network through a competitive learning algorithm. SOM is used for clustering and mapping (or dimensionality reduction) technique
4 min read
Overview of Kalman Filter for Self-Driving Car
A Kalman Filter is an optimal estimation algorithm. It can help us predict/estimate the position of an object when we are in a state of doubt due to different limitations such as accuracy or physical constraints which we will discuss in a short while. Application of Kalman filter: Kalman filters are used when – Variable of interest that can only be
8 min read
How To Use Self With Decorator?
Python decorators are a powerful and flexible feature that allows you to modify or extend the behavior of functions or methods. When working with methods in classes, it's essential to understand how to use self them with decorators. The self keyword refers to the instance of the class, and incorporating it with decorators can provide a way to enhan
3 min read
Create Derived Class from Base Class Universally in Python
In object-oriented programming, the concept of inheritance allows us to create a new class, known as the derived class, based on an existing class, referred to as the base class. This facilitates code reusability and structuring. Python provides a versatile way to create derived classes from base classes universally, allowing for flexibility and sc
3 min read
Call a Class Method From another Class in Python
In object-oriented programming, classes play a pivotal role in organizing and structuring code. Python, being an object-oriented language, allows the creation of classes and their methods to facilitate code modularity and reusability. One common scenario in programming is the need to call a method from one class within another class. In this articl
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Violinplot in Python using axes class of Matplotlib
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. #Sample Code # Implementation of matplotlib functi
2 min read
Matplotlib.ticker.MultipleLocator Class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.ticker.MultipleLocator The matplotlib.ticker.MultipleLocator class is used for setting a tick for every integer multiple of a b
1 min read
fromisoformat() Function Of Datetime.date Class In Python
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date
2 min read
Matplotlib.gridspec.GridSpec Class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.gridspec.GridSpec The matplotlib.gridspec.GridSpec class is used to specify the geometry of the grid to place a subplot. For th
3 min read
Matplotlib.patches.CirclePolygon class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.patches.CirclePolygon The matplotlib.patches.CirclePolygon class is used for polygon-approximation of a circle patch. It is use
3 min read
Python Psycopg - Cursor class
The cursor class Enables Python scripts to use a database session to run PostgreSQL commands. The connection class is what creates cursors. cursor() method: They are permanently connected to the connection, and all instructions are run in the context of the database session covered by the connection. Cursors generated from the same connection aren'
5 min read
Python | Avoiding class data shared among the instances
Class attributes belong to the class itself and they will be shared by all the instances and hence contains same value of each instance. Such attributes are defined in the class body parts usually at the top, for legibility. Suppose we have the following code snippet : C/C++ Code # Python code to demonstrate # the working of the sharing # of data v
2 min read
Python Tkinter | Create different type of lines using Canvas class
In Tkinter, Canvas.create_line() method is used to create lines in any canvas. These lines can only be seen on canvas so first, you need to create a Canvas object and later pack it into the main window. Syntax: Canvas.create_line(x1, y1, x2, y2, ...., options = ...) Note: Minimum of 4 points are required to create a line, but you can also add multi
2 min read
Python Tkinter | Create different shapes using Canvas class
In Tkinter, Canvas class is used to create different shapes with the help of some functions which are defined under Canvas class. Any shape that Canvas class creates requires a canvas, so before creating any shapes a Canvas object is required and needs to be packed to the main window. Canvas Methods for shapes: Canvas.create_oval(x1, y1, x2, y2, op
3 min read
How to create a list of object in Python class
We can create a list of objects in Python by appending class instances to the list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C. Let's try to understand it better with the help of examples. Exampl
2 min read
rangev2 - A new version of Python range class
range() is a built-in function of Python. It is used when a user needs to perform an action for a specific number of times. The range() function is used to generate a sequence of numbers. But the sequence of numbers produced by range is generally either decreasing or increasing linearly which means it is either incremented and decremented by a part
2 min read
Print objects of a class in Python
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object.
2 min read
Python: Call Parent class method
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. Example: # Python program to demonstrate # classes class cls: # Constructor def __init__(self, fname,
4 min read
Overriding Nested Class members in Python
Overriding is an OOP's (object-oriented programming) concept and generally we deal with this concept in Inheritance. 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
2 min read
How to Get a List of Class Attributes in Python?
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 it for maintaining its state. Class instances can
4 min read
Inheritance in Python Inner Class
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 it for maintaining its state. Class instances can
3 min read
Python - Access Parent Class Attribute
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 it for maintaining its state. Class instances can
4 min read
Extend Class Method in Python
In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism. This is similar to overriding in Java and virtual methods
3 min read
Matplotlib.colors.Normalize class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.colors.Normalize The matplotlib.colors.Normalize class belongs to the matplotlib.colors module. The matplotlib.colors module is
3 min read
Matplotlib.colors.LogNorm class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.colors.LogNorm() The matplotlib.colors.LogNorm() class belongs to the matplotlib.colors module. The matplotlib.colors module is
3 min read
Practice Tags :