static methods in python | what is static method in python |
Static Methods:-
Static Method are method that are related to a class in same way, but don’t need to access any class specific data. You don’t have to use self and you don’t even need to instantiate an instance. You simplify call your method.
Static Method |
What Is Static Method -
Static Method in python are extremely similar to python class level method. The difference being that static method is bound to class rather than object for that class. This means that a static method can be call without an object for that class. This also means that static method can not modify the state of an object as they are not bound to it.
Creating Python Static Method -
Using @staticmethod-
The @staticmethod is a built in decorator in python which defines a static method.
A static method doesn't receive any reference argument whenever it is called by an instance of a class or by the class itself.
following notation is used to declare a static method in a class .
Syntax –
Class ClassName:
@staticmethod
def function_name():
#function body
Program -
class Person :
@staticmethod
def msg():
print("hello")
@staticmethod
def msg():
print("hello")
In above example @staticmethod is applied to the msg() method . so the msg() method can be called using the class name Persone.msg() as well as using the object .
Accessing static method Using Class_Name
Person.msg()
Output -
hello
Accessing static method Using an Object
ob=Person() # creating an object
ob.msg() # accessing static method Using object
ob.msg() # accessing static method Using object
Output -
hello
Class Method
Post a Comment