Python Static method

 Static Method:

The static method in python class is achieved by using built-in decorator called @staticmethod or staticmethod()

By using static method we can call the method in class with or without creating an objectWhich means that static method is bound to a class rather than the objects of that class.

Since creating object is not necessary in static method we no need to include self as parameter in methods.

Note: As self is the reference of object

Using @staticmethod in class:
class Lion:

@staticmethod # create static method for portray using decorator
def portray():
print('Lion is king of the jungle')

Lion.portray() # with out creating object calling the method

obj = Lion() # creating object
obj.portray() # calling the method using object

Output:


Using staticmethod() in class:
class Lion:

def portray():
print('Lion is king of the jungle')

Lion.portray =staticmethod(Lion.portray) # create static method for portray
Lion.portray() # with out creating object calling the method

obj = Lion() # creating object
obj.portray() # calling the method using object

Output:

Comments

Popular posts from this blog

Switch frame in selenium python

Learn basics of python collection data type (list, tuple, dictionary and set) instantly

Python property method