Python3 定义常量,无法导入模块
高洛峰
高洛峰 2016-10-28 13:35:04
0
1
917

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

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语法变了吗?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(1)
三叔

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!