推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
henryho914
V2EX  ›  Python

请问一个关于定义常量的报错信息

  •  
  •   henryho914 · Dec 1, 2015 · 2673 views
    This topic created in 3841 days ago, the information mentioned may be changed or developed.
    你好,我是刚学习 python,版本是 python3.x 的,今天写了一个 const 的文件,用于定义常量,如果重复赋值就会报错,但是现在的问题是,报错信息却不是我的预期信息,请问是怎么回事呢?

    const.py
    ====================================================
    import sys
    class ConstError(TypeError):pass

    class _const(object):
    def __setattr__(self,name,value):
    if name in self.__dict__:
    raise self.ConstError("Can't rebind const(%s)"%name)
    self.__dict__[name]=value

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


    useConst
    ===================================================
    import const

    const.value = 12
    const.value = 13
    print (const.value)


    报错信息:
    Traceback (most recent call last):

    AttributeError:'_const'object has no attribute 'ConstError'

    我的预期抛错信息应该是 Can't rebind const(value)的,请问是怎么回事呢?
    5 replies    2015-12-13 22:49:07 +08:00
    henryho914
        1
    henryho914  
    OP
       Dec 1, 2015
    已解决.................
    class ConstError(TypeError):pass
    这个类放错位置了
    xiangace
        2
    xiangace  
       Dec 3, 2015
    安利下我的作品 kkconst
    xiangace
        3
    xiangace  
       Dec 3, 2015   ❤️ 1
    henryho914
        4
    henryho914  
    OP
       Dec 3, 2015
    @xiangace
    谢谢你的代码,学习了不少~
    xiangace
        5
    xiangace  
       Dec 13, 2015
    @henryho914 那个库实现的代码写复杂了, 可以看我的一篇文章, 由简单的需求衍生出来的库的历史,
    大致上是一个演进的过程, 提供 metaclass 的使用案例, 可能帮助你理解你现在的场景需求.
    [ 应用于 Restful 接口的错误码设计 – ErrorCode Class(Python) ]( http://www.kaka-ace.com/restful_api_error_code_design_for_python/)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1050 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 23:06 · PVG 07:06 · LAX 16:06 · JFK 19:06
    ♥ Do have faith in what you're doing.