V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
yueyoum
V2EX  ›  Python

求助, attribute is read-only

  •  
  •   yueyoum ·
    yueyoum · 2016-07-25 10:56:31 +08:00 · 2686 次点击
    这是一个创建于 2824 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码里一直这么写的

    class MyClass(object):
        __slots__ = ['xx', ]
        def __init__(self):
            self.xx = 1
    

    但是刚才 用了 pycharm 2016.2 后 pycharm 提示说

    'MyClass' object attribute 'xx' is read-only

    这是什么意思? 既然是 read-only 为何代码一直能跑? 以前版本的 pycharm 没这个提示。

    如何消除这个提示?

    4 条回复    2016-07-26 15:35:18 +08:00
    LPeJuN6lLsS9
        1
    LPeJuN6lLsS9  
       2016-07-26 12:07:12 +08:00   ❤️ 1
    把设置>编辑器>inspections 里的 access to properties 关掉试试?我的 py3.4 没有出现,但重点是为什么会出现这提示
    yueyoum
        2
    yueyoum  
    OP
       2016-07-26 13:49:28 +08:00
    @hantsuki 谢谢, 按照你的办法, 现在没有那种提示了。

    我也不知道为什么 __slots__ 中定义的 属性 就是只读的。。。
    LPeJuN6lLsS9
        3
    LPeJuN6lLsS9  
       2016-07-26 15:01:45 +08:00
    问题的根源有点神奇: IDE 是对的,他说 MyClass 的属性 xx 是只读的,确实如此。虽然可以无视警告赋值,但是赋过一次之后再实例化 MyClass 就会报错,死在“ self.xx = 1 ”

    应该是 py 的一个坑
    yueyoum
        4
    yueyoum  
    OP
       2016-07-26 15:35:18 +08:00
    @hantsuki
    确实是 python 的坑

    代码里不能有 MyClass.xx = XX
    否则 类有了 类变量, xx 确实是 只读的...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1048 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:42 · PVG 06:42 · LAX 15:42 · JFK 18:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.