python-靜態成員函式和classmethod裝飾器
阿新 • • 發佈:2019-01-26
1. python類中定義的變數,如果不加self就不歸屬於類,只有在第一次例項化時進行初始化
class Count1: count = 0 def __init__(self): Count1.count +=1 self.num = 1 # count += 1 不允許 def get_count(self): return Count1.count a1 = Count1() a2 = Count1() a2.num = 2 print("a1[%s:%s]a2[%s:%s]" % (a1.get_count(),a1.num,a2.get_count(),a2.num) ) print(Count1.get_count())
執行結果:
[email protected] ~/test_demo $ python classmethod2.py
a1[2:1]a2[2:2]
Traceback (most recent call last):
File "classmethod2.py", line 15, in <module>
print(Count1.get_count())
TypeError: get_count() missing 1 required positional argument: 'self'
通過執行結果中num的的區別,可以看出Count1物件確實生成了兩個例項,而兩個例項中count都等於2,可見當a2在構造過程中並沒有初始化count變數到0,所以在類中直接定義的變數可認為靜態變數。
並且count在類中進行呼叫時候不允許在成員函式中直接使用,比如第六行會被識別為未定義。因此這種變數不屬於單個例項。
2. classmethod
相對與上邊的程式碼就多了一行@classmethod來修飾get_count()
class Count1: count = 0 def __init__(self): Count1.count +=1 self.num = 1 # count += 1 不允許 @classmethod def get_count(self): return Count1.count a1 = Count1() a2 = Count1() a2.num = 2 print("a1[%s:%s]a2[%s:%s]" % (a1.get_count(),a1.num,a2.get_count(),a2.num) ) print(Count1.get_count())
檢視執行結果:
[email protected] ~/test_demo $ python classmethod2.py
a1[2:1]a2[2:2]
2
現在可以看到直接用Count1這個類名就可以呼叫到get_count函式,也就是說get_count函式此時不歸屬於a1,a2例項,因此可以說加上classmethod修飾後的函式,變成了靜態成員函式。
總結:
class裡直接定義且不帶self的變數是靜態成員變數,只在第一次例項化該類時被初始化。加上classmethod修飾的成員函式會成為靜態成員函式,不再歸屬於例項。