Friday, June 15, 2012

Python Static Class Variable 的行爲

隨手記下今天遇到的 Python Static Class Variable 的行爲:

>>> class Test():
... REQUESTS_PER_SECOND = 1
...


直接訪問:

>>> Test.REQUESTS_PER_SECOND
1


重新賦值,instance 繼承新值:

>>> Test.REQUESTS_PER_SECOND = 2
>>> t = Test()
>>> t.REQUESTS_PER_SECOND
2


再次重新賦值,instance 再次繼承新值:

>>> Test.REQUESTS_PER_SECOND = 3
>>> t.REQUESTS_PER_SECOND
3


instance 賦值,對 static class variable 無影響:

>>> t.REQUESTS_PER_SECOND = 4
>>> Test.REQUESTS_PER_SECOND
3


已賦值過的 instance 不再受 class 的影響:

>>> Test.REQUESTS_PER_SECOND = 5
>>> t.REQUESTS_PER_SECOND
4

1 comment:

abrianatakamoto said...

The King Casino (2021) | CommunityKhabar
The King Casino is a casino in Southern California 바카라사이트 and is owned by the King bet365 Group of Casinos. In this review, we cover all aspects of 더킹카지노 it and the casino