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
Post a Comment