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

I hit an interesting python bug today in which instantiating a class repeatedly appears to be holding state. In later instantiation calls the variable is already defined.

I boiled down the issue into the following class/shell interaction. I realize that this is not the best way to initialize a class variable, but it sure should not be behaving like this. Is this a true bug or is this a "feature"? :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 prompt:

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'}

解决方案

It is a feature that pretty much all Python users run into once or twice. The main usage is for caches and the like to avoid repetitive lengthy calculations (simple memoizing, really), although I am sure people have found other uses for it.

The reason for this is that the def statement only gets executed once, which is when the function is defined. Thus the initializer value only gets created once. For a reference type (as opposed to an immutable type which cannot change) like a list or a dictionary, this ends up as a visible and surprising pitfall, whereas for value types, it goes unnoticed.

Usually, people work around it like this:

def test(a=None):

if a is None:

a = {}

# ... etc.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值