python中有关常量的问题

python中有没有常量

      在python中没有常量的,但可以自己设置常量。有两种方法

第一种方法

class MyMath(object):
	def __init__(self):
		self.__PI = "3.1415926"
	def PI(self):
		return self.__PI
math = MyMath()
print(math.PI())  # 常量这个不能让别人修改的值,只能获取,这样我们就能得到__PI的值了

第二种方法

class MyMath(object):
	def __init__(self):
		self.__PI = "3.1415926"

	@property
	def PI(self):
		return self.__PI

math = MyMath()
print(math.PI)  # 常量这个不能让别人修改的值,这样看起来就像是获取一个常量了

猜你喜欢

转载自blog.csdn.net/gllaxq/article/details/80266089