在 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 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.