Python self Variable
Python self Variable
Python self variable is used to bind the instance of the class to the instance method. We have to explicitly declare it as the first method argument to access the instance variables and methods. This variable is used only with the instance methods.
In most of the Object-Oriented programming languages, you can access the current object in a method without the need for explicitly having it as a method parameter. For example, we can use “this” keyword to access the current object in Java program. But, in Python we have to explicitly declare the object instance as “self” variable
Example1:
class Emp:
def __init__(self, name, empid):
self.name = name
self.empid = empid
print(id(self))
def e1(self):
print("Name of Emp: ", self.name)
print("Emp id is : ", self.empid)
e = Emp('VDS', 100)
print(id(e))
e.e1()
POINTS TO REMEMBER:
- Python self variable is not a reserved keyword. But, it’s the best practice and convention to use the variable name as “self” to refer to the instance.
- The self variable gives us access to the current instance properties.
- self : self represents the instance of the class. By using the "self" keyword all the attributes and methods of the python class can be accessed.
- Use self when:
- you define an instance method, since it is passed automatically as the first parameter when the method is called.
- you reference a class or an instance attribute from inside an instance method;
- you want to refer to instance variables and methods from other instance methods.
Example-2:
class Student:
def __init__(self,name, rollNo):
self.name = name
self.rollNo = rollNo
def m1(self):
print('Name of Student: ', self.name)
print('rollNo of Student: ', self.rollNo)
@staticmethod
def sum(a, b):
return a + b
@classmethod
def m2(cls):
print("This is class method!!")
s1 = Student('VDS', 100)
s1.m1()
Student.m2()
print(Student.sum(10, 20))
s
Comments
Post a Comment