Maison  >  Questions et réponses  >  le corps du texte

Python3 定义常量,无法导入模块

我按照网上的方法自定义了一个常量类,如下:

class _const:
    """
    自定义常量:(1)命名全部大写;(2)值不可修改
    """
    class ConstError(TypeError):
        pass

    class ConstCaseError(ConstError):
        pass

    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            raise self.ConstError('Can not change const.{0}'.format(name))
        if not name.isupper():
            raise self.ConstCaseError(
                'const name {0} is not all uppercase.'.format(name))
        self.__dict__[name] = value


import sys
sys.modules[__name__] = _const()


import const
const.PLACEHOLDER = '请输入您的待办事项'
const.EMPTY_LIST_ERROR = '待办事项不可为空!'

运行时报错:

File "/home/chris/Workdir/django_gtd/gtd/constant.py", line 23, in <module>
    import const
ImportError: No module named 'const'

请问是Python3语法变了吗?

高洛峰高洛峰2913 Il y a quelques jours923

répondre à tous(1)je répondrai

  • 三叔

    三叔2016-10-28 13:35:49

    const.py

    if self.__dict__.haskey(name):
    改为
    if name in self.__dict__.keys():

    class _const:
        """
        自定义常量:(1)命名全部大写;(2)值不可修改
        """
        class ConstError(TypeError):
            pass
    
        class ConstCaseError(ConstError):
            pass
    
        def __setattr__(self, name, value):
            #if self.__dict__.haskey(name):
            if name in self.__dict__.keys():
                raise self.ConstError('Can not change const.{0}'.format(name))
            if not name.isupper():
                raise self.ConstCaseError(
                    'const name {0} is not all uppercase.'.format(name))
            self.__dict__[name] = value
    
    
    import sys
    sys.modules[__name__] = _const()

    test.py

    import const
    const.PLACEHOLDER = '请输入您的待办事项'
    const.EMPTY_LIST_ERROR = '待办事项不可为空!'

    2个文件分别保存,并且在同一个文件夹里。
    运行test.py

    répondre
    0
  • Annulerrépondre