解釋 Python 中類 __init__() 函式內外變數。


類變數與例項變數

Python 中 __init__函式以外的所有變數都是類變數,而函式內部的是例項變數。透過檢視下面的程式碼可以更好地理解類變數和例項變數之間的區別

示例

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

更新日期: 13-Jun-2020

已瀏覽 1 千次

開啟您的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.