Python常量工具類


1.定義常量類constant.py

# -*- coding: utf-8 -*
"""常量工具類

author: Jill

usage:
    from constant import _Const
    const = _Const()
    const.PI = 3.14
"""


class _Const:
    class ConstError(TypeError):
        pass

    class ConstCaseError(ConstError):
        pass

    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise self.ConstError("Can't change const(%s) value" % name)
        if not name.isupper():
            raise self.ConstCaseError("Const name %s is not all uppercase" % name)

        self.__dict__[name] = value

    def __getitem__(self, key):
        if key in self.__dict__:
            return self.__dict__[key]
        else:
            raise self.ConstError("Can't return const %s, No Existing Key!" % key)

    def __delattr__(self, name):
        if name in self.__dict__:
            raise self.ConstError("Can't unbind const(%s)" % name)
        raise NameError(name)

 

2.將常量放在一個模塊中common_constant.py

# -*- coding: utf-8 -*
"""常用常量定義

author: Jill

usage:
    from common_constant import const
    print(const.ROOT_PATH)
"""
from common.constant import _Const


const = _Const()

const.PI = 3.14

if __name__ == "__main__":
    print(const.PI)
    print(const['PI'])

 

3.在其他模塊里使用test.py

from common_constant import const
    

print(const.ROOT_PATH)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM