Static Method in Python

 

Static Method in Python


To define static method, @staticmethod decorator is used, method defined under @staticmethod decorator are static method

 
#program to define static method
 class Employee_data :
@staticmethod
def operations():
print("this is static method")


  • Static Method perform operation on static variables.


#program

class Employee_data :
website =
"AETies"
@staticmethod
def operations():
print("\nwebsite : ", Employee_data.website)

Employee_data.operations()
# calling static method with class name

emp_1 = Employee_data()
emp_1.operations()
# calling static method with class name

 #Output

website : AETies

website : AETies


  • Class name can be used to call static method.

#program

class Employee_data :
website =
"AETies"
@staticmethod
def operations():
print("\nwebsite : ", Employee_data.website)
print("this is static method,\noperation on static variables can only be performed by static method,\n"
"static method gets memory at class loading time,\n"
"so can directly access by class name without creating object,\n"
"static method can be access by class name and object\n")

Employee_data.operations()
# calling static method with class name

 #Output

website : AETies
this
is static method,
operation on static variables can only be performed by static method,
static method gets memory at class loading time,
so can directly access by class name without creating object,
static method can be access by class name and object


  • Static method can be called with object as well.

#program

class Employee_data :
website =
"AETies"
@staticmethod
def operations():
print("\nwebsite : ", Employee_data.website)
print("this is static method,\noperation on static variables can only be performed by static method,\n"
"static method gets memory at class loading time,\n"
"so can directly access by class name without creating object,\n"
"static method can be access by class name and object\n")

emp_1 = Employee_data()
emp_1.operations()
# calling static method with object

 #Output

website : AETies
this
is static method,
operation on static variables can only be performed by static method,
static method gets memory at class loading time,
so can directly access by class name without creating object,
static method can be access by class name and object


Static Method can not access "cls"(class method) and "self"(instance method) variables.





Comments

My photo
Techno Xpresss
Bangalore, Karnataka, India