如何在一个类中定义一些常量,每个对象都可以方便访问这些常量而不用重新构造?
class Document():
WELCOME_STR = 'Welcome! The context for this book is {}.'
a=Document()
print type(a)
print dir(a)
print a.WELCOME_STR
C:Python27python.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 {}.