Python论坛  - 讨论区

标题:[python-chinese] two questions

2005年08月09日 星期二 20:06

limodou limodou at gmail.com
Tue Aug 9 20:06:22 HKT 2005

在 05-8-9,小楼听雨<hailang_0512 at 163.com> 写道:
>  
> def foo(par=[]):
>     if par is None:
>         par = []
>         par.append(0)
>     print par 
>   
> foo()
> print foo.func_defaults 
>   
> foo()
> print foo.func_defaults 
>   
> foo([9])
> print foo.func_defaults 
>   
> foo()
> print foo.func_defaults
>  
> 结果是: 
> []          
> ([],) #为什么不是([0],)
因为foo.func_defaults是缺省参数,而你的判断是par is
None,但缺省值却是[],因此判断为假,if里面的语句根本没执行,自然缺省值不会变了。而且还有一个问题是par =
是一个赋值语句,因此执行它会产生一个新的对象,而失去对原来对象[]的绑定。也就是说if中的par与缺省值的par所绑定的不是一个对象。
> []
> ([],)
> [9]
> ([],)
> []
> ([],) 
>  难道是par.append(0)的问题? 

因为判断是is None,因此你的所有调用都运行不到if的分支中,缺省值自然没有改掉。

把par = [] 去掉试试。

-- 
I like python! 
My Donews Blog: http://www.donews.net/limodou
New Google Maillist: http://groups-beta.google.com/group/python-cn

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号