Open In App

self in Python class

Last Updated : 18 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Python3




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.

Python3




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.

Python3




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.

Python3




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.

Python3




# 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.

Python3




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


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
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Practice Tags :
three90RightbarBannerImg