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


類變數與例項變數

Python 中 class __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-六月-2020

1 千 + 瀏覽量

開啟您的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.