Python基础之常量
在Python中没有一个专门的语法代表常量,但约定俗成用变量名全部大写的变量代表常量。
Python中没有真正的常量,为了迎合其他语言的口味,全部大写的变量称之为常量。
Python的常量必须满足两个条件:
- 命名全部为大写
- 值一旦被绑定便不可再修改
C
1 | int * const pi |
Python
1 | PI = 3.14 |
用自定义类实现常量与使用:
引用博客:https://blog.csdn.net/qq_17034717/article/details/81942059用自定义类实现常量:const.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18# -*- coding: utf-8 -*-
# python 3.x
# Filename:const.py
# 定义一个常量类实现常量的功能
#
# 该类定义了一个方法__setattr()__,和一个异常ConstError, ConstError类继承
# 自类TypeError. 通过调用类自带的字典__dict__, 判断定义的常量是否包含在字典
# 中。如果字典中包含此变量,将抛出异常,否则,给新创建的常量赋值。
# 最后两行代码的作用是把const类注册到sys.modules这个全局字典中。
class _const:
class ConstError(TypeError):pass
def __setattr__(self,name,value):
if name in self.__dict__:
raise self.ConstError("Can't rebind const (%s)" %name)
self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()在项目中引用常量
1
2
3import const
const.PI=3.14
print(const.PI)
本文作者:
Charles Yang
本文链接: https://blog.xmysql.com/20200602/Python%E5%9F%BA%E7%A1%80%E4%B9%8B%E5%B8%B8%E9%87%8F.html
版权声明: 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!
本文链接: https://blog.xmysql.com/20200602/Python%E5%9F%BA%E7%A1%80%E4%B9%8B%E5%B8%B8%E9%87%8F.html
版权声明: 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!