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
pc10201
V2EX  ›  Python

python 静态变量的问题

  •  
  •   pc10201 · 2015-08-30 19:58:18 +08:00 · 2492 次点击
    这是一个创建于 3167 天前的主题,其中的信息可能已经有所发展或是发生改变。
    # coding=utf-8
    
    class Linux (object ):
        name = 'linux'
        hardware = {'cpu': 'intel', 'disk': '500G'}
    
    
    l1 = Linux ()
    l1.name = 'CentOS'
    l1.hardware['cpu'] = 'amd'
    
    l2 = Linux ()
    
    print l2.name, l2.hardware
    

    输出结果

    linux {'disk': '500G', 'cpu': 'amd'}

    name 和 hardware 都属于静态变量,为什么修改了 name 不影响另一个实例,而修改了 hardware 就会呢?

    4 条回复    2015-09-04 16:32:31 +08:00
    KIDJourney
        1
    KIDJourney  
       2015-08-30 20:11:57 +08:00
    因为 hardware 是一个引用,他指向了一个字典。
    你在修改的过程中并没有修改引用本身,而是修改了指向的字典的值。

    你如果把

    l1.hardware['cpu'] = 'amd'

    改为

    l1.hardware = {'cpu':'amd','disk':'500G'}

    就不会出现这种状况。
    leavic
        2
    leavic  
       2015-08-30 20:22:55 +08:00
    所以 python 会建议你把类成员数值的初始化放到_init_函数里去,这样可以避免这个问题。
    ljcarsenal
        3
    ljcarsenal  
       2015-08-30 20:39:33 +08:00
    可变类型和不可变类型的区别,以及类变量和实例变量的区别
    wingor2015
        4
    wingor2015  
       2015-09-04 16:32:31 +08:00
    @ljcarsenal 嗯, c 系列语言过来的人容易被坑
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2300 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 08:51 · PVG 16:51 · LAX 01:51 · JFK 04:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.