Python论坛  - 讨论区

标题:[python-chinese] 看看这段代码?

2005年07月08日 星期五 16:06

guqi guqi at oasisnet.com.cn
Fri Jul 8 16:06:55 HKT 2005

在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

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

2005年07月08日 星期五 16:40

Qiangning Hong hongqn at gmail.com
Fri Jul 8 16:40:20 HKT 2005

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

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

2005年07月08日 星期五 17:27

guqi guqi at oasisnet.com.cn
Fri Jul 8 17:27:58 HKT 2005

看来我用的是方案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

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

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

    你的回复:

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

    Zeuux © 2025

    京ICP备05028076号