Python 中的類變數還是靜態變數?
當我們在類外部但方法內部宣告變數時,在 Python 中被稱為類變數或靜態變數。類變數或靜態變數可以透過類引用,但不能直接透過例項引用。
類變數或靜態變數與同名其他成員變數完全不同,並且不會與它們衝突。以下程式演示了類變數或靜態變數的使用方法,−
示例
class Fruits(object):
count = 0
def __init__(self, name, count):
self.name = name
self.count = count
Fruits.count = Fruits.count + count
def main():
apples = Fruits("apples", 3);
pears = Fruits("pears", 4);
print (apples.count)
print (pears.count)
print (Fruits.count)
print (apples.__class__.count) # This is Fruit.count
print (type(pears).count) # So is this
if __name__ == '__main__':
main()結果
3 4 7 7 7
另一個演示在類級別定義變數的示例 −
示例
class example: staticVariable = 9 # Access through class print (example.staticVariable) # Gives 9 #Access through an instance instance = example() print(instance.staticVariable) #Again gives 9 #Change within an instance instance.staticVariable = 12 print(instance.staticVariable) # Gives 12 print(example.staticVariable) #Gives 9
輸出
9 9 12 9
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP