Course
Static Methods
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Static Methods
is that the static method doesn't have a mandatory argument like reference to the object − self or reference to the class − cls. Python's standard library fimction
staticmethod()
returns a static method.
In the Employee class below, a method is converted into a static method. This static method can now be called by its object or reference of class itself.
class Employee: empCount = 0 def __init__(self, name, age): self.__name = name self.__age = age Employee.empCount += 1 #@staticmethod def showcount(): print (Employee.empCount) return counter = staticmethod(showcount)
e1 = Employee("Bhavana", 24)e2 = Employee("Rajesh", 26)e3 = Employee("John", 27)
e1.counter()Employee.counter()
Python also has
@staticmethod
decorator that conveniently returns a static method.@staticmethod def showcount(): print (Employee.empCount)e1.showcount()Employee.showcount()
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.