Skip to content

Instantly share code, notes, and snippets.

@nature-python
Last active August 29, 2015 13:57
Show Gist options
  • Save nature-python/9596307 to your computer and use it in GitHub Desktop.
Save nature-python/9596307 to your computer and use it in GitHub Desktop.
python中如何实现静态语言的const

Python 中常量的实现

实现方法来源于**《Python Cookbook》**,发放就是把值放在这个对象的__dict__字典中,当增加或者改变值的时候就在__dict__中寻找是否,有则报错,否则则存入

class _const(object):
	class ConstError(TypeError):
		pass
	def __setattr__(self,name,value):
		if self.__dict__.has_key(name):
			raise ConstError("can't rebind const (%s)"%name)
		self.__dict__(name)=value
c=_const()
c.a=2
c.a=3#报错
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment