在Python中定义类变量的正确方法是什么?
类变量是在__init__方法之外声明的变量。这些是静态元素,也就是说,它们属于类而不是类实例。这些类变量由该类的所有实例共享。类变量的示例代码
示例
class MyClass:
__item1 = 123
__item2 = "abc"
def __init__(self):
#pass or something else使用更多代码,您将更加清楚地了解-
class MyClass:
stat_elem = 456
def __init__(self):
self.object_elem = 789
c1 = MyClass()c2 = MyClass()# Initial values of both elements
>>> print c1.stat_elem, c1.object_elem
456 789
>>> print c2.stat_elem, c2.object_elem
456 789
# Let's try changing the static element
MyClass.static_elem = 888
>>> print c1.stat_elem, c1.object_elem
888 789
>>> print c2.stat_elem, c2.object_elem
888 789
# Now, let's try changing the object element
c1.object_elem = 777
>>> print c1.stat_elem, c1.object_elem
888 777
>>> print c2.stat_elem, c2.object_elem
888 789热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短