Python學習筆記 常量定義

2022-02-26 13:13:08 字數 603 閱讀 9909

在python中沒有提供定義常量的保留字,需要自己定義乙個常量類來實現常量的功能!在此提供《python cookbook》一書中定義的常量模組const,**如下:

說明:此類是定義了乙個方法__setattr__()和乙個異常型別consterror,主要是判斷定義的常量是否在字典中,在則丟擲異常,否則,給新建立的常量賦值

code

1class

_const:

2class

consterror(typeerror):

pass

3def__setattr__

(self,name,value):

4ifself.

__dict__

.has_key(name):

5raise

self.consterror,

"can't rebind const (%s)"%

name

6self.

__dict__

[name]

=value78

import

sys9

sys.modules[

__name__]=

_const()

C 學習筆記 常量定義

include iostream using namespace std define pi 3.14159 const double pi 3.14159 intmain intargc,char argv include iostream using namespace std define p...

python語言常量 Python 定義常量

python python開發 python語言 python 定義常量 常量在編寫程式的時候,一旦設定就不能再進行變動,常量一種約定俗成的方式,所有字母大寫並用下劃線分隔單詞的方式 如max value,out time等 但是python沒有提供設定常量用法,需要自己自定義類實現常量功能。自定義...

Python定義常量

i 訪問字典的元素使用dobj.get key somethingelse 如果對應key值元素不存在,你將會得到somethingelse值,例如 not found 不要使用dobj key 因為如果key對應元素不存在,則會產生keyerror異常,這樣必須使用try except來封裝 ii...