您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中定义类变量的正确方法

在Python中定义类变量的正确方法

两种方法都不一定正确或不正确,它们只是两种不同的类元素:

您将通过一些代码更清楚地看到它:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

如您所见,当我们更改class元素时,这两个对象都发生了变化。但是,当我们更改对象元素时,另一个对象保持不变。

python 2022/1/1 18:45:29 有311人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶