Python3声明常量
来源:互联网 发布:mac开机启动迅雷 编辑:程序博客网 时间:2024/06/03 13:55
以下代码可在jupyter、pycharm等上使用
首先声明一个常量类:
class _const(object):
class ConstError(PermissionError): pass
def __setattr__(self, name, value):
if name in self.__dict__.keys():
raise self.ConstError( "Can't rebind const(%s)" % name)
self.__dict__[name] = value
def __delattr__(self, name):
if name in self.__dict__:
raise self.ConstError("Can't unbind const(%s)" % name)
raise NameError(name)
import sys
sys.modules[__name__] = _const()
声明后的使用:
constant = _const()
constant.value = 3 #value常量值3
constant.maxVal = 15 #maxVal 常量值15
print(constant.value) #输出3
print(constant.maxVal)
若再对constant.value赋值:constant.value = 4
报错如下:
----> 7 raise self.ConstError( "Can't rebind const(%s)" % name) 8 self.__dict__[name] = value 9 ConstError: Can't rebind const(value)
常量值不可更改。则constant.value和constant.maxVal就可作为常量使用了。----Python初学者小小经验----
- Python3声明常量
- Const常量声明
- 文件常量声明
- 表常量声明
- php之 声明常量
- Oracle 声明常量
- 声明和使用常量
- JQuery声明常量
- delphi const常量声明演示
- java声明变量和常量
- ES6 变量、常量声明总结
- PHP常量声明、使用方法|define()函数定义常量类似于全局
- PHP常量的声明和使用
- php常量的声明和使用
- 3.3 声明和使用常量;3.4 术语
- swift之声明常量和变量
- 为什么接口里声明的都是常量
- iOS 常量的声明和实现
- redis-主从配置
- 蚂蚁森林的新发现
- Redis系列~字符串(String)(六)
- POJ 3040 贪心
- 用canvas实现钟表功能
- Python3声明常量
- Tomcat启动失败:端口被占用
- 成功安装mysql后,为何服务管理器里找不到MYSQL服务名和mysql安装出现Install/RemoveoftheServiceDenied!
- 网站头部 html
- Redis系列~哈希(Hash)(七)
- LeetCode 119. Pascal's Triangle II
- 2016.10.27打表 距NOIP23天
- Is the Information Reliable?--差分约束系统
- Angular2 typescript 中英文教程