如何在一個類中定義一些常量,每個對象都可以方便訪問這些常量而不用重新構造?

如何在一個類中定義一些常量,每個對象都可以方便訪問這些常量而不用重新構造?

class Document():
    WELCOME_STR = 'Welcome! The context for this book is {}.'
a=Document()
print type(a)
print dir(a)
print a.WELCOME_STR

C:\Python27\python.exe "C:/Users/TLCB/PycharmProjects/untitled2/python study/t12.py"
<type 'instance'>
['WELCOME_STR', '__doc__', '__module__']
Welcome! The context for this book is {}.


一種很常規的做法,是用全大寫來表示常量,因此我們可以在類中使用 self.WELCOME_STR ,


或者在類外使用 Entity.WELCOME_STR ,來表達這個字符串。


在類外:

node2:/root/python/object#cat t100.py
class Document():
    WELCOME_STR = 'Welcome! The context for this book is {}.'
node2:/root/python/object#
node2:/root/python/object#cat t1.py 
from  t100 import *;
print Document.WELCOME_STR
node2:/root/python/object#
node2:/root/python/object#python t1.py 
Welcome! The context for this book is {}.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章