Python define your own constants class

1. Constant use of each letter in uppercase letters, the intermediate connector underlined: as MAX_VALUE;

2. Once bound value of the constant can not modify.

As the value of the constant is no longer binding once modified, so that is the time constant of the second assignment requires thrown. So we obviously need to rewrite the assignment method constants class custom. In Python, when we assign values ​​to properties of the class, it will automatically call __setattr object class __ () function, the function is defined as follows:

object.__setattr__(self, name, value)

Where name represents the name of the property, value is the value of trying to assign the name, object .__ dict__ which object class holds all valued attributes in the form of a dictionary.

So we can define a class constant constant class (default inherited from object), and the object .__ setattr __ () method is overridden. Because there are two constant rule, so we need two custom exception handling in accordance with these rules, and exception handling are non-capitalized names exception handling secondary assignment.

Define constants categories:

constant.py
import sys

class _const:
    # custom exception handler
    class ConstError (PermissionError):
        Pass
    class ConstCaseError (ConstError):
        Pass
    # rewrite __setattr __ () method
    DEF __setattr __ (Self, name, value):
        IF name in Self .__ dict__ magic: # Incl. the constant, the secondary can not assign
            the raise self.ConstError ( "Change can not const {0}" the format (name).)
        IF not name.isupper (): # all letters capitalized
            raise self.ConstCaseError ( "const name Not All IS 0} {UPPERCASE ".format (name))
        Self .__ dict __ [name] = value

# The list of modules in the system constant loading replaced _const () Example
sys.modules [__ name__] = _const ( )

Constants defined in another file, the test.py
Import Constant
constant.VALUE. 5 =
= #. 4 constant.VALUE ConstError
constant.vaLue. 1 = # ConstCaseError

When we identify the images or modify the value of the constant VALUE definition of a name is not all caps constant, will throw an exception, so that to achieve the aim of constant value can not be changed.

Guess you like

Origin www.linuxidc.com/Linux/2019-06/159051.htm