|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 yamal 于 2017-3-11 22:11 编辑
import const
const.NAME = 'FishC'
print(const.NAME)
try:
#尝试修改常量
const.NAME = 'FishC.com'
except TypeError as Err:
print(Err)
try:
#变量名需要大写
const.name = 'FishC'
except TypeErrpr as Err:
print(Err)
================================================================
class Const:
def __setattr__(self,name,value):
if name in self.__dict__:
raise TypeError('常量无法改变!')
if not name.isupper():
raise TypeError('常量必须由大写字母组成!')
self.__dict__[name] = value
import sys
sys.modules[__name__] = Const()
保存在const.py文件中
====================================================================
ost recent call last):
File "C:\Users\lvhao\Desktop\21课None.py", line 1, in <module>
import const
File "<frozen importlib._bootstrap>", line 1567, in _find_and_load
File "<frozen importlib._bootstrap>", line 1553, in _find_and_load_unlocked
File "C:\Users\lvhao\Desktop\const.py", line 7, in __setattr__
raise TypeError('常量必须由大写字母组成!')
TypeError: 常量必须由大写字母组成!
====================================================================
这个是小甲鱼老师50课课后习题的最后一题。
第二段代码是保存在const.py中的。
为什么我运行第一段代码出现的结果是以上这样的呢?
而小甲鱼的结果是:
>>>
FishC
常量无法改变!
常量名必须由大写字母组成! |
|