- SELF in Python
- What is Self?
- Is the self a keyword?
- Why self ought to be the first parameter of instance methods
- What is the difference between self and __init__?
- What Is ‘self’ in Python? A Complete Guide (with Examples)
- The ‘self’ Keyword in Python
- Example: A Fruit Class
- How Does ‘self’ Work in the Example?
- Store Anything to Self in Python
- Example
- A Method without ‘self’ Argument in a Python Class
- Proof That Self Refers to the Object Itself
- Self Is Not a Reserved Keyword in Python
- Conclusion
- Further Reading
SELF in Python
Every professional or student using Python will have to create an instance of a class anytime during his programming career. We use it using the self keyword. Programmers use it in method definition or initialization of variables. This article is about the self parameter along with what is self in Python? What does it do? How to use it and some other crucial topics related to SELF.
What is Self?
The self parameter is a reference to the instance of a class. It aids in accessing the variables which belong to a class. One can use any other name like mine or me instead of self. It should be the first parameter in the function of a class while defining the function.
Here are 2 example:
class chkr: def __init__(self): print("The address of self in this class is: ", id(self)) obj = chkr() print("The address of class object is: ", id(obj))
class Student: def __init__(myobj, name, age): myobj.name = name myobj.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Student("Joydeep", 25) p1.myfunc()
Here is another example of using the self parameter:
class sucar(): # init method or constructor def __init__(self, name, color): self.name = name self.color = color def show(self): print("The car's name is", self.name ) print("And, its color is", self.color ) # both the objects have a different self that contains their attributes Supra = sucar("Supra", "blue") Mercedes = sucar("Mercedes", "green") Supra.show() # same output as car.show(Supra) Mercedes.show() # same output as car.show(Mercedes)
Is the self a keyword?
Self acts as a keyword in other programming languages like C and C++. In Python, self is a parameter in a method definition. Professionals state that using self enhances the code readability. One can replace self with anything else as the first parameter of a method like mine, obj, etc.
Follow the below example:
class myClass: def show(other): print(“other in place of self”)
Why self ought to be the first parameter of instance methods
Let’s take the help of an example:
class Rect (): def __init__(self, x = 0, y = 0): self.x = x self.y = y def ar (self): return (self.x * self.y) rec1=Rect(6,10) print ("The rectangle's area is:", rec1.ar())
In the above example, __init__ passed two arguments but defined three parameters, likewise the area().
Here, rect.ar and rec1.ar in the above code are different.
>>> type(Rectangle.area ) >>> type(rec1.area)
Here, Rectangle.area is a function, and rec1.area is a method. Python has a unique feature that allows passing an object as the first argument in any function.
Here, rec1.area() and Rectangle.area(rec1) are similar
Commonly, the related class function gets called by putting the method’s object before the first argument when the method gets called with some arguments.
That means obj.method(args) transforms to class.method(obj, args). That’s why self ought to be the first parameter of instance methods in Python.
What is the difference between self and __init__?
- Self: It is the instance of a class. With the help of self, one can access all the methods and attributes of a Python class.
- __init__: It is a reserved method of Python classes. It is a constructor in OOP concepts. Whenever an object gets created from a class, __init__ gets called. It enables the class to initialize class attributes.
The self parameter is a reference to the instance of a class. The reason Python programmers need to use self is that in Python we do not implement the @ syntax for referring to the instance attributes.
Accessing the instances through self is much faster and can smoothly work with the members associated with the class. It aids in accessing the variables which belong to a class. It can have other names instead of self.
It behaves as a keyword in programming languages except for Python. In Python, self is a convention that programmers follow, a parameter in a method definition.
- Python Training Tutorials for Beginners
- Square Root in Python
- Python vs PHP
- pip is not recognized
- Python Factorial
- Python Continue Statement
- Python lowercase
- Python map()
- Polymorphism in Python
- Inheritance in Python
- Python : end parameter in print()
- Python zip()
- Id() function in Python
- Python Split()
- Only Size-1 Arrays Can be Converted to Python Scalars
- Bubble Sort in Python
- Python list append and extend
- Python Sort Dictionary by Key or Value
- Python KeyError
- Python Return Outside Function
What Is ‘self’ in Python? A Complete Guide (with Examples)
With self, you are able to access the attributes and methods of the class.
For instance, this Fruit class assigns a custom name and color to itself upon creation. These can then be accessed by the info() method:
class Fruit: def __init__(self, name, color): self.name = name self.color = color def info(self): print(self.color, self.name) banana = Fruit("Banana", "Yellow") banana.info()
To understand how this works, let’s dive deeper into the details of self in Python.
This guide is intended for someone who already knows about classes but the concept of self is a bit vague. If you are unfamiliar with Python classes, please check this guide.
The ‘self’ Keyword in Python
In Python, a class is a blueprint for creating objects.
Each Python object is representative of some class. In Python, an object is also called an instance of a class. If you want to create an object in Python, you need to have a class from which you can create one.
A typical Python class consists of methods that perform actions based on the attributes assigned to the object.
For instance, a Weight class could store kilograms and have the ability to convert them to pounds.
In a Python class, the self parameter refers to the class instance itself. This is useful because otherwise there would be no way to access the attributes and methods of the class.
Example: A Fruit Class
To understand self better, let’s take a look at a simple Fruit class. This Fruit class lets you create Fruit objects with a custom name and a color:
class Fruit: def __init__(self, name, color): self.name = name self.color = color def info(self): print(self.color, self.name)
Now you can create Fruit objects this way:
banana = Fruit("Banana", "Yellow") apple = Fruit("Apple", "Red")
And you can show info related to them:
How Does ‘self’ Work in the Example?
Let’s examine how this Fruit class works.
When you create a new Fruit object, the __init__ method is called under the hood. It is responsible for creating objects. Let’s inspect the __init__ method of the Fruit class to see what is going on. It takes three arguments:
When you create a Fruit object, the __init__ method is called with the custom name and color. Notice how you do not need to pass self as an argument. Python does it automatically for you.
So, when you call banana = Fruit(“Banana”, “Red”):
- The __init__ method starts initializing the banana object with the given name and color arguments.
- It creates new attributes self.name and self.color and stores the input name and color to them.
- After this, it is possible to access the name and the color attributes of the banana anywhere in the object via self.name or self.color.
Let’s also see what happens when you call banana.info().
When you call banana.info(), Python automatically passes the self into the method call as an argument under the hood. The info() method can then use self to access the name and color attributes of the object. Without self, it would not be able to do that.
Store Anything to Self in Python
Previously, you saw how the self parameter can be used to store attributes to the objects.
More specifically, you saw the typical approach where you pass __init__ method arguments and assign them to self using the same name:
def __init__(self, name, color): self.name = name self.color = color
This may raise the question “Do the argument names have to equal to what is assigned to the self?” The answer is no.
Similar to how you can create any variable anywhere in Python, you can assign any attributes to an object via self.
This means you can store any values with any names to self. They do not even have to be given as arguments in the __init__ function.
Example
For example, let’s create a class Point that represents a point in 3D space. Let’s initialize the Point objects in the origin without asking for the points as arguments upon initialization.
To do this, assign x, y, and z values of 0 to self in the __init__ method:
class Point: def __init__(self): self.x = 0 self.y = 0 self.z = 0
Now you can create Point objects to the origin:
The point here is to demonstrate how you can freely add any attributes to an object’s self property.
A Method without ‘self’ Argument in a Python Class
In Python, a method needs the self argument. Otherwise, it doesn’t know the class it belongs to and is unable to perform actions on it.
To see what happens if a method doesn’t accept the self argument, let’s leave self out from the info() method:
class Fruit: def __init__(self, name, color): self.name = name self.color = color def info(): print(self.color, self.name) banana = Fruit("Banana", "Yellow") banana.info()
Traceback (most recent call last): File "main.py", line 10, in banana.info() TypeError: info() takes 0 positional arguments but 1 was given
The last line suggests that the info() method takes no arguments, but we gave it one. But based on the above code, it seems you didn’t give any arguments. So why does the interpreter still think you gave it some?
Even though you do not give the info() method any arguments, Python automatically tries to inject self into the call. This is because Python knows all methods in a class need to have a reference to the class itself to work properly. But in our implementation of info(), there’s no argument self. Thus passing self argument into it behind the scenes will fail.
This shows you that you need to use the self argument in methods.
Proof That Self Refers to the Object Itself
For the sake of clarity, let me prove that the self indeed refers to the object itself.
To do this, let’s check the memory locations of self and a Fruit object.
In Python, you can check the memory address of an object with the id() function. (Here I have simplified the Fruit class to make it easier to digest):
class Fruit: def __init__(self): print("Self address =", id(self)) fruit = Fruit() print("Object address EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Self address = 140243905604576 Object address = 140243905604576
As you can see, the memory addresses are equal. This shows you that self inside the Fruit class points to the same address as the fruit object you just created. In other words, the self parameter really refers to the object itself.
Self Is Not a Reserved Keyword in Python
Notice that self is not a reserved keyword in Python. You could use any name you like instead as long as there’s one.
For instance, let’s change the implementation of the Fruit class from earlier sections. This time, let’s use the name this instead of self:
class Fruit: def __init__(this, name, color): this.name = name this.color = color def info(this): print(this.color, this.name) banana = Fruit("Banana", "Yellow") apple = Fruit("Apple", "Red")
This code works the exact same way as the one that used self.
But because self is so commonly used among Python developers, it’s advisable not to use anything else. You are unlikely to encounter anything else than self when working with classes in Python.
Conclusion
Today you learned what self does in a Python class.
To recap, self in Python refers to the object itself. It is useful because this way the class knows how to access its own attributes and methods.
When you create an object, the __init__ method is invoked. In this method, you typically assign attributes to the class instance via self.
Notice how the self is not a reserved keyword. You could use whatever instead of self, as long as you pass it as the first argument for each method of the class. However, self is so commonly used that you should not use anything else, even though it is possible.
Thanks for reading. I hope you found what you were looking for. Happy coding!