Friday, April 16, 2021

Static Methods in Python - Example of a Static Method in a Class in Python

 


    Static Methods in Python


* One can use Static Methods while the class level but one may not involve the class or the constituting instances .

 

* Static Methods are used when one wants to process an element in relation to a class but does not need the class or its instance to perform any work .

 

* Example :

writing the environmental variables that go inside creation of a class , counting the number of instances of the class or changing an attribute in another class are the tasks related to a class .. such tasks can be handled by Static Methods

 

* Static Methods can be used to accept some values , process the values and then return the result .

 

* Also one could use Static Methods to accept some values , process the values and then return the result

 

* In this case , the involvement of neither the class nor the objects is of paramount importance .

 

* Static methods are written with a decorator @staticmethod above the methods

 

* Static Methods are called in the form of classname,method()

 

* In the following method , one is creating a static method "noObjects()" that counts the number of objects or instances created in MyClass . In MyClass , one can write a constructor that increments the class variable 'n' everytime an instance of the class is created . This incremented value of 'n' gets displayed by the "noObject()" method

  


 

No comments:

Post a Comment