关于类:如何在Python中声明静态属性?

How to declare a static attribute in Python?

如何在python中声明静态属性?

下面是我如何声明一个方法:python中的静态方法?


在python的类级别上定义的所有变量都被认为是静态的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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)

类中可以有两个同名的不同变量(一个静态变量和一个普通变量)。不要困惑。


类"body"中声明的所有变量都是"static"属性。

1
2
3
4
5
6
7
class SomeClass:
    # this is a class attribute
    some_attr = 1

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

但请记住,"静态"部分是由约定而不是强加的(有关此方面的更多详细信息,请阅读此so线程)。

关于本公约及其含义的更多细节,以下是官方文件的一个简短摘录:

"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 (e.g. _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.


只需添加到其中,函数中也可以有静态变量,而不仅仅是类:

1
2
3
4
5
6
7
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

静态属性是Python中的数据属性。以便类中分配的属性:

1
2
3
4
5
>>>class A(object):
>>>    a = 1

>>>A.a
>>>1

这与C++和Java不同,其中静态成员不能使用实例访问:

1
2
3
4
>>>inst  = A()
>>>inst.a
1
>>>

另外,内置方法setattr将帮助您设置static variable(data attribute)

1
2
3
>>>setattr(A, 'b', 2)
>>>A.b
>>>inst.b


可以使用标准@property decorator生成静态属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
class A(object):
    @property
    def a(self):
        return 1

a = A()
print a.a

1

a.a = 2

AttributeError: can't set attribute