2005年07月08日 星期五 16:06
在python里,实参和形参如何表示和传入. >>> def change(a): a='op' >>> a=89 >>> change(a) >>> a 89 >>> def change(a): a='op' return a >>> a 89 >>> change(a) 'op' >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20050708/b66e8697/attachment-0001.html
2005年07月08日 星期五 16:40
guqi wrote: > 在python里,实参和形参如何表示和传入. > > >>> def change(a): > a='op' > >>> a=89 > >>> change(a) > >>> a > 89 [...] 函数内部的a是局部名字,重新绑定它不影响外界。 方案一:用global .>> a = 89 .>> def change_a(): ... global a ... a = 'op' ... .>> change_a() .>> a 'op' 方案二:用返回值 .>> a = 89 .>> def change(a): ... return 'op' ... .>> a = change(a) .>> a 'op' 方案三:用mutable object作参数 .>> a = [89] .>> def change(a): ... a[0] = 'op' ... .>> change(a) .>> a ['op'] 或者用class包装 .>> class A: ... def __init__(self, a): ... self.a = a ... .>> a = A(89) .>> a.a 89 .>> def change(a): ... a.a = 'op' ... .>> change(a) .>> a.a 'op' -- Qiangning
2005年07月08日 星期五 17:27
看来我用的是方案2,3ks了. 看来python里在定义上没有明确的区分,实参和变参了. 了解. ----- Original Message ----- From: "Qiangning Hong" <hongqn at gmail.com> To: <python-chinese at lists.python.cn> Sent: Friday, July 08, 2005 4:40 PM Subject: Re: [python-chinese] 看看这段代码? > guqi wrote: > > 在python里,实参和形参如何表示和传入. > > > > >>> def change(a): > > a='op' > > >>> a=89 > > >>> change(a) > > >>> a > > 89 > [...] > > 函数内部的a是局部名字,重新绑定它不影响外界。 > > 方案一:用global > > .>> a = 89 > .>> def change_a(): > ... global a > ... a = 'op' > ... > .>> change_a() > .>> a > 'op' > > 方案二:用返回值 > > .>> a = 89 > .>> def change(a): > ... return 'op' > ... > .>> a = change(a) > .>> a > 'op' > > 方案三:用mutable object作参数 > > .>> a = [89] > .>> def change(a): > ... a[0] = 'op' > ... > .>> change(a) > .>> a > ['op'] > > 或者用class包装 > > .>> class A: > ... def __init__(self, a): > ... self.a = a > ... > .>> a = A(89) > .>> a.a > 89 > .>> def change(a): > ... a.a = 'op' > ... > .>> change(a) > .>> a.a > 'op' > > > -- > Qiangning > _______________________________________________ > python-chinese list > python-chinese at lists.python.cn > http://python.cn/mailman/listinfo/python-chinese
Zeuux © 2025
京ICP备05028076号