From this , you will get to learn about method. It is one of the essential concepts to use while you are learning OOPs programming with Python.

Note: The syntax used in the below section is for Python 3. You may it to use with a different version of Python.

Python Static Method

To Learn about OOPs Concepts – Read Python Class

What is a static method in Python?

It is available as a built-in function in Python and allows you to turn a regular method into the static.

In other words, you can create a callable class using the static method and use it with some restrictions.

It helps developers write code in a safe architectural way to prevent conflicts in the code.

How does the Python Static method work?

When you create a class, you usually define a few methods and properties. They may or may not have access to the class instance.

There three types of methods depending upon their access are Instance Method, Class Method, and Static Method. This tutorial will cover the application of Static Methods.

It is a method which does not have access to the class state. In other words, the method confines to itself and cannot change the properties of the class instance without any workaround.

You can make use of “staticmethod” in your programs with the following syntax:

class class_name:
    def object_behaviour:
        //Code to be executed

Alternatively, you can follow the below syntax:



Function returning a value as static:

Here is a simple program to demonstrate static methods.

class Math:
    def Multiply(one, two):
        return one * two
math = Math()
if(12*72 == math.Multiply(12, 72)):
    print("Not Equal")

the above code as “” and execute. The output will come as:

Python static method example-1  - Python static method example 1 - Python Static Method Usage Explained with Examples

A method as static:

Check another program to use the built-in staticmethod() function.

class Person:
    def Age(age):
        if(age <= 30):
        elif(age>30 and age<=50):
            print("Middle Age")
            print("Senior Age")
John = Person
Type_of_age = staticmethod(John.Age(45))

Save the above code as “” and execute. The output will come as:

Python static method example-2  - Python static method example 2 - Python Static Method Usage Explained with Examples



Source link


Please enter your comment!
Please enter your name here