- 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__?
- Python Self Parameter
- The Python “self” Parameter
- How to Use “self” in Python?
- Conclusion
- About the author
- Haroon Javed
- Python Classes and Objects
- Create a Class
- Example
- Create Object
- Example
- The __init__() Function
- Example
- The __str__() Function
- Example
- Example
- Object Methods
- Example
- The self Parameter
- Example
- Modify Object Properties
- Example
- Delete Object Properties
- Example
- Delete Objects
- Example
- The pass Statement
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
Python Self Parameter
Python is an object-oriented programming language that allows you to define classes and create class objects. Classes are blueprints that contain attributes (data) and methods (functions) that belong to the objects. Objects are representations of classes that can interact with each other. To access the object attributes and methods within a class, the “self” parameter is used in Python.
This write-up presents a complete guide on the “self” parameter via the below-supported contents:
The Python “self” Parameter
In Python, the “self” parameter is a special keyword that is utilized to refer to the existing instance of a class. It is always the first parameter in a method definition and is utilized to access/retrieve the attributes and methods of the current/existing instance.
Note: The “self” parameter is needed because it allows us to retrieve the current object attributes and methods. By not including the “self” parameter, we would not be able to refer to the current object, and we would not be able to access/call its attributes and methods.
How to Use “self” in Python?
To use “self” in Python, we need to define a class and a function within the class that takes “self” as the first parameter. After that, we can use “self” to access/call the object attributes and methods.
Example 1: Basic Working of the Python “self” Parameter
The below code shows the working of the “self” parameter in Python:
class company:
def __init__ ( self, name, age ) :
self.name = name
self.age = age
def func1 ( self ) :
print ( «Hello, my name is » + self.name )
p1 = company ( «Joseph» , 15 )
p1.func1 ( )
-
- The class with two attributes, “name” and “age”, is defined in the code.
- The “__init__()” function is a special method that is accessed when an object is constructed/created. It is utilized to initialize the object attributes. The “self” parameter assigns the values of “name” and “age” to the object.
- The “func1()” function is a regular method that accepts “self” as a parameter. It uses “self.name” to access the “name” object attribute.
- The class object is created from the class, and the values for “name” and “age” are passed as arguments.
- The “dot” notation is employed to call the “func1()” method via the created object.
The function’s value has been displayed successfully.
Here are other examples of the “self” parameter to help us better understand its usage.
Example 2: Using “self” With Another Name
The “self” is not a keyword in Python; it is just a practice that most Python programmers follow. We can use any other name instead of “self” as long as it is the function’s first parameter:
class company:
def __init__ ( cap, name, age ) :
cap.name = name
cap.age = agedef func1 ( cap ) :
print ( «Hello, my name is » + cap.name )
p1 = company ( «Joseph» , 15 )
p1.func1 ( )In the above code, the “self” is changed to “cap”, and this works exactly the same as before.
The function value has been displayed successfully.
Note: However, using “self” is highly recommended as it makes your code more readable and consistent with other Python code. It also helps avoid confusion with other variables with similar names.
Example 3: Using “self” in Static Method and Class Method
The “Class” methods are the methods that take the class as the first argument in place of the instance. They are marked with the “@classmethod” decorator. They can be used to access or modify class attributes or to create new instances of the class.
The “Static” methods, however, don’t accept any parameters and don’t depend on the instance or the class. They are marked with the “@staticmethod” decorator. The class’s members can be used to perform some utility functions without accessing its state:
class calculation:
x = 5.5
y = 4.5
@ classmethod
def circle_area ( cls, radius ) :
return cls.x * radius ** 2
@ staticmethod
def add ( x, y ) :
return x + y
print ( calculation.circle_area ( 5 ) )
print ( calculation.add ( 3 , 4 ) )-
- The class “calculation” is defined with two class attributes named “x” and “y”. It also contains one class method and one static method.
- The “cls” parameter is used to refer to the class itself. It is similar to “self”, but for class methods, we can use “cls.x” to access the class attributes.
- The static methods don’t use “self” or “cls” parameters. They just perform some calculations using the arguments.
- To call the class or the static methods, object creation is not required. We can just use the class name and dot notation.
Conclusion
When referring to the current instance of a class, we utilize the “self” parameter to access the class’s variables and functions. The “self” is not a keyword and can be replaced by any other name, although it is not recommended. This article discussed Python’s “self” parameter using numerous examples.
About the author
Haroon Javed
Hi, I’m Haroon. I am an electronics engineer and a technical content writer. I am a tech geek who loves to help people to the best of my knowledge.
Python Classes and Objects
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a «blueprint» for creating objects.
Create a Class
To create a class, use the keyword class :
Example
Create a class named MyClass, with a property named x:
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
The __init__() Function
The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = ageNote: The __init__() function is called automatically every time the class is being used to create a new object.
The __str__() Function
The __str__() function controls what should be returned when the class object is represented as a string.
If the __str__() function is not set, the string representation of the object is returned:
Example
The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = ageExample
The string representation of an object WITH the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = ageObject Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
Let us create a method in the Person class:
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = agedef myfunc(self):
print(«Hello my name is » + self.name)p1 = Person(«John», 36)
p1.myfunc()Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = agedef myfunc(abc):
print(«Hello my name is » + abc.name)p1 = Person(«John», 36)
p1.myfunc()Modify Object Properties
You can modify properties on objects like this:
Example
Delete Object Properties
You can delete properties on objects by using the del keyword:
Example
Delete the age property from the p1 object:
Delete Objects
You can delete objects by using the del keyword:
Example
The pass Statement
class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.