Programming Tutorials

Static in python

By: Vijay in Python Tutorials on 2012-04-07  

In Python, the static keyword is not used like in some other programming languages like Java or C++. However, there are some ways to achieve a similar effect.

One common way to simulate a static method in Python is by using the staticmethod decorator. This decorator can be applied to a method inside a class to indicate that it should be a static method. A static method is a method that belongs to the class itself, rather than to any specific instance of the class. This means that it can be called on the class directly, rather than on an instance of the class.

Here's an example:

class MyClass:
    @staticmethod
    def my_static_method():
        print("This is a static method.")

MyClass.my_static_method()

In this example, my_static_method() is decorated with @staticmethod, which indicates that it should be a static method. It can then be called directly on the class MyClass, without needing to create an instance of the class.

Another way to achieve a similar effect in Python is to use class-level variables. These are variables that are defined directly inside a class, rather than inside a method. Class-level variables are shared across all instances of the class, so they can be thought of as static variables.

Here's an example:

class MyClass:
    my_static_variable = "This is a static variable."

print(MyClass.my_static_variable)

In this example, my_static_variable is defined directly inside the MyClass class, outside of any methods. This means that it is a class-level variable, which can be accessed directly on the class itself.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)