Python Static Methods: Self-Contained Functions in Classes

thumb_up 1  ·  sell Python static methods, Static functions in Python classes, Defining static methods in Python

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()
 
 
 
 
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back