Instance Method in Python

 

Instance Method


To define instance method, no decorator is used.

 #program to define instance class

class Employee_data :
def operations(self):
print("this is instance method")

  • Instance Method take "self " as default parameter. 

# program to define instance class

class Employee_data:
def operations(self):
self.a = 10
self.b = 20
print("result : ", self.a + self.b)


  • Instance Method gets memory at object creation time.

#program

class Employee_data:
def operations(self):
self.a = 10
self.b = 20
print("result : ", self.a + self.b)

Employee_data.operations()            # calling by class name before creating object

my_data = Employee_data()
my_data.operations()

 #Output

Traceback (most recent call last):
File "
C:/Self_Practice_Er_M_S_Dandyan/Python/Pycharm/xml/main.py", line 9, in <module>
Employee_data.operations()
TypeError: operations() missing 1 required positional argument: 'self'



  • Object is used to access instance method.

#program

class Employee_data:
def operations(self):
self.a = 10
self.b = 20
print("result : ", self.a + self.b)

my_data = Employee_data()
my_data.operations()

 #output

result : 30


  • Instance Method will perform operation on instance variables.

#program

class Employee_data:
def operations(self):
self.a = 10
self.b = 20

def disply_operation(self):
self.operations()
print("a :", self.a)
print("b :", self.b)
print("a + b :", self.a + self.b)

my_data = Employee_data()
my_data.disply_operation()

 #Output

a : 10
b : 20
a + b : 30


  • Instance Method can perform operation on "cls" and static variables 

#program

class Employee_data:

website =
"AETies"

@classmethod
def class_operation(cls):
cls.a = 10

def operations(self):
self.b = 20

def disply_operation(self):

self.class_operation()
self.operations()
print("website", Employee_data.website)
print("a :", self.a)
print("b :", self.b)
print("a + b :", self.a + self.b)

my_data = Employee_data()
my_data.disply_operation()

 #Output

website AETies
a :
10
b : 20
a + b : 30






Comments

My photo
Techno Xpresss
Bangalore, Karnataka, India