小编cbr*_*ker的帖子

为什么通过python默认变量初始化变量会在对象实例化中保持状态?

我今天遇到了一个有趣的python bug,其中实例化一个类似乎反复出现状态.在以后的实例化调用中,已经定义了变量.

我将问题归结为以下类/ shell交互.我意识到这不是初始化类变量的最佳方法,但它肯定不应该像这样.这是一个真正的错误还是这个"功能"?:d

tester.py:

class Tester():
        def __init__(self):
                self.mydict = self.test()

        def test(self,out={}):
                key = "key"
                for i in ['a','b','c','d']:
                        if key in out:
                                out[key] += ','+i
                        else:   
                                out[key] = i 
                return out

Python提示:

Python 2.6.6 (r266:84292, Oct  6 2010, 00:44:09) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
>>> import tester
>>> t = tester.Tester()
>>> print t.mydict
{'key': 'a,b,c,d'}
>>> t2 = tester.Tester()
>>> print t2.mydict
{'key': 'a,b,c,d,a,b,c,d'}

python arguments

6
推荐指数
2
解决办法
7117
查看次数

标签 统计

arguments ×1

python ×1