在 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

更新于: 20-Feb-2020

143 次浏览

开启你的 职业生涯

完成课程即可获得认证

开始
广告