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

test_list[1].group.append(test_list[0].name)出错

  •  
  •   magine ·
    Ma233 · 2014-03-30 19:11:34 +08:00 · 2433 次点击
    这是一个创建于 3678 天前的主题,其中的信息可能已经有所发展或是发生改变。
    代码如下

    class test:
    group = []
    def __init__(self,name):
    self.name = str(name)



    test0 = test(0)
    test1 = test(1)

    test_list = [test0,test1]
    test_list[0].group.append(test_list[1].name)
    #此时print test0.group 是['1'],这是把test1.name存入test0.group中。
    test_list[1].group.append(test_list[0].name)
    #但是在执行了上一句之后print test0.group 却变成了['1','0']
    #我在上一句中为什么会改变test0的值?
    #顺便一提这时print test1.group 会变成['1','0'],而不是预计的['0']
    4 条回复    1970-01-01 08:00:00 +08:00
    magine
        1
    magine  
    OP
       2014-03-30 19:12:31 +08:00
    天哪……缩进全没了……大神们凑合着看吧QAQ
    bcxx
        2
    bcxx  
       2014-03-30 19:37:56 +08:00   ❤️ 1
    group 是 test 这个类的属性,test0 test1 引用的都是同一个 group
    sorcerer
        3
    sorcerer  
       2014-03-30 19:43:57 +08:00 via iPhone   ❤️ 1
    虽然我是Python初学者,但也看出你的group是个类变量,当你访问实例变量时,如果实例没有那个属性,就返回类变量的值,所以你操作的都是类变量。最后类名首字母请用大写。
    magine
        4
    magine  
    OP
       2014-03-30 20:04:11 +08:00
    @bcxx
    多谢了,燃眉之急啊QAQ。是我基础知识不扎实……
    @sorcerer
    我猜是初学者啊,泪……
    啊抱歉,调试程序的时候卡在这里了,急着构造一个样例,疏忽风格了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1315 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 23:37 · PVG 07:37 · LAX 16:37 · JFK 19:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.