Open In App

Self Type in Python

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 Python

In this example, we are going to write a simple program to explain when we are going to return to the class itself and what will happen.

Python3




# Define a class
class Car:
    def set_brand(self, brand: str) -> Car:
        self.brand = brand
        return self
 
# call set_brand method
Car().set_brand("Maruti")


Output: This program will return an error that “name ‘car’ is not defined”

Returning an instance of a class using Self type in Python

In this example, we are going to resolve the error that we faced in the previous example by making the use of new Self Type in Python. By using Self we can able to make the function that returns an instance of a class. As we can see in the output when we are calling the function of a class it does not give any output and we are able to print objects using the print statement.

Python3




# Import Self
from typing import Self
 
# Define a base class
class Car:
    def set_brand(self,
                  brand: str) -> Self:
        self.brand = brand
        return self
 
# Define a child class
class Brand(Car):
    def set_speed(self,
                  speed: float) -> Self:
        self.speed = speed
        return self
 
# Calling object inside print statement
print(Car().set_brand("Maruti"))
print(Brand().set_brand("Mar\
uti").set_speed(110.5))
print(type(Car().set_brand("Maruti")))
print(type(Brand().set_brand("Maruti").set_speed(110.5)))


Output:

<__main__.Car object at 0x000002365E33F3D0>
<__main__.Brand object at 0x000002365E33F3D0>
<class '__main__.Car'>
<class '__main__.Brand'>


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads