python如何使用不可变量const

点击量:15

# python2
# Put in const.py...:
class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__.has_key(name):
            raise self.ConstError, "Can't rebind const(%s)"%name
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()
# that's all -- now any client-code can
import const
# and bind an attribute ONCE:
const.magic = 23
# but NOT re-bind it:
const.magic = 88      # raises const.ConstError
# you may also want to add the obvious __delattr__

# python3 version
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()

这样一来,就可以在python中使用不可变量了。其中,利用魔术方法__setattr__,把一个变量当作是const类的属性,然后使用__dict__来判断当前变量是否已经存在。

通过这个技巧我们还能构造出一系列有意思的东西——

运行截图

refer

  • https://gist.github.com/Svtter/c96e3259e264621e8bc1ab45b4c2675a
  • http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991

发表评论

电子邮件地址不会被公开。 必填项已用*标注