How to declare a static attribute in Python?

How can I declare a static attribute in Python?

Here is written how I can declare a method: Static methods in Python?


All variables defined on the class level in Python are considered static

class Example:
    Variable = 2           # static variable

print Example.Variable     # prints 2   (static variable)

# Access through an instance
instance = Example()
print instance.Variable    # still 2  (ordinary variable)


# Change within an instance 
instance.Variable = 3      #(ordinary variable)
print instance.Variable    # 3   (ordinary variable)
print Example.Variable     # 2   (static variable)


# Change through Class 
Example.Variable = 5       #(static variable)
print instance.Variable    # 3  (ordinary variable)
print Example.Variable     # 5  (static variable)

You can have two different variables in your class under the same name (one static and one ordinary). Don't be confused.


All variables declared inside the Class' body are 'static' attributes.

class SomeClass:
    # this is a class attribute
    some_attr = 1

    def __init__(self):
        # this is an instance attribute
        self.new_attr = 2

But keep in mind that the 'static' part is by convention, not imposed (for more details on this, read this SO thread).

For more details of this convention and its implications, here is a quick excerpt from the official documentation:

“Private” instance variables that cannot be accessed except from inside an object, don't exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (eg _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.


为了增加它,你可以在函数中使用静态变量,而不仅仅是类:

def some_fun():
    some_fun.i += 1
    print(some_fun.i)

some_fun.i = 0;
print(some_fun(), some_fun(), some_fun())  
# prints: 1,2,3  
链接地址: http://www.djcxy.com/p/55142.html

上一篇: 实现UUID作为主键

下一篇: 如何在Python中声明静态属性?