Static class member in Python

Asked 2 years ago, Updated 2 years ago, 104 views

Can I create a static member variable or function in the Python class? What grammar should I use?

class-variables class python static method

2022-09-21 17:58

1 Answers

Variables declared inside a class, not inside a function, are class or static variables:

>>> class MyClass:
...     ...     i = 3
...
>>> MyClass.i
3 

The above code generates a class-level variable "i" but is completely different from the instance-level "i". So you can see the results below.

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

This is somewhat different from C++ or Java, but it looks similar to C#, which does not have access to static members by referring to the instance.

See the Python tutorial covering classes and class objects.

Also, if you look at the content of Built-in Functions" in the Python Library Reference, you will find how to create a static function.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

Some people recommend the classmethod rather than the staticmethod in terms of accepting the class type as the first parameter, but I'm not sure how it benefits you more than the staticmethod. If you don't feel a big advantage like me, you can just use the static method.


2022-09-21 17:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.