曲则全,枉则直,洼则盈,敝则新,少则得,多则惑。 是以圣人抱一为天下式。不自见,故明;不自是,故彰;不自伐,故有功;不自矜,故长。

Python函数传参方式

上一篇 / 下一篇  2010-01-24 21:03:05 / 个人分类:脚本语言

Python是脚本语言,不像C一样,会声明是int,char或是float
比如有一个类,构造函数需要两个参数,然后打印出来。
class mytest():
    def __init__(self,param1,param2):
        print 'this is the first parameter',param1
        print 'this is the second parameter',param2

if __name__=='__main__':
    c1=mytest('a','b')
    print ''
    c2=mytest(1,2)

这时运行一下,显然结果是
this is the first parameter a
this is the second parameter b

this is the first parameter 1
this is the second parameter 2

然后参数用数组来构造,在c2=mytest(1,2)下面添加
    x=['a','b']
    c3=mytest(x)
运行后报错,提示“__init__() takes exactly 3 arguments (2 given)”
这是因为Python把【x】这个数组传给了param1,而没有给param2传值。可以将上面的构造函数做个更改,添加默认值为None
class mytest():
    def __init__(self,param1=None,param2=None):
        print 'this is the first parameter',param1
        print 'this is the second parameter',param2

if __name__=='__main__':
    x=['a','b']
    c3=mytest(x)
运行以后,结果是
this is the first parameter ['a', 'b']
this is the second parameter None

如果想用数组传参,那需要调用时,用*(字典是用**)
    将 c3=mytest(x)改为:
    c4=mytest(*x)
运行结果就是
this is the first parameter a
this is the second parameter b
假设要用字典,那调用时,应该用**kwargs,如:
    y={'param1':'a','param2':'b'}
    c5=mytest(**y)

做个小总结,如果没有*,或**,Python会把不管是数组也好,字典也好,统统传给一个参数,而如果用*,或**,就会对应给各个参数。
补充:
1.如果字典用*,会怎么样?
    c6=mytest(*y)
输出的是y这个字典的key值
2.如果数组的元素个数,大于函数定义的个数会怎么样
会出错。
但是,如果把上面的代码改为
class mytest():
    def __init__(self,param1=None,param2=None,*args):
        print 'this is the first parameter',param1
        print 'this is the second parameter',param2
        print args

if __name__=='__main__':
    x=['a','b','c','d']
    c=mytest(*x)
会输出
this is the first parameter a
this is the second parameter b
('c', 'd')
就是把多出来的部分,扔到args这个元组了。()是元组,[]是数组。
3.如果定义函数时使用元组或字段,默认就是一个空的。
class mytest():
    def __init__(self,*args):
        print args
        print type(args)

if __name__=='__main__':
    c=mytest()
输出
()
<type 'tuple'>


TAG:

高山流水 引用 删除 love¥¥   /   2012-06-07 11:04:20
很好
 

评分:0

我来说两句

日历

« 2024-04-24  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 46387
  • 日志数: 33
  • 文件数: 1
  • 建立时间: 2009-07-10
  • 更新时间: 2010-12-07

RSS订阅

Open Toolbar