Cookbook 6.2 defines Constants

Source: Internet
Author: User

Task:

Some module-level variables (such as named constants) need to be defined, and the customer Code cannot re-bind them;

Solution:

#coding = utf-8class _const(object):    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    def __delattr__(self,name):        if name in self.__dict__:            raise self.ConstError,"Can‘t unbind const(%s)" % name        raise NameError,name    import syssys.modules[__name__] = _const()

Usage:

1. Save the preceding code as Const. py and add the directory of the file to the SYS. Path directory;

2. Run Const. py.

3. input the following in Python shell:

Import const

# Test code

Const. Magic = 23

Note: currently, any customer code can import const and bind one attribute of the const module once, but only once;

Once an attribute has been bound, the program cannot rebind it or unbind it.

Const. Magic = 99 # Throw Const. consterror

Del Const. Magic # Throw Const. consterror

 

Cookbook 6.2 defines Constants

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.