您的位置:首页 > 编程语言 > C语言/C++

python 像C语言样的函数参数引用实现..

2014-02-25 12:29 387 查看
python中有传参需求,好像也没有像C一样传参(引用)设计,可以采用一种变形方式,函数返回值来实现。

def test():
        t1 = "123123"
        t2 = "test"
        t3 = 122
        t4 = 1.12
        return t1, t2, t3, t4

t1, t2, t3, t4 = test()
print t1, t2, t3, t4


这种方式不是很好看,还可以采用其他的方法:

1) 上面说的函数返回值,可以说成使用元祖返回的方式。

2)通过可变化的对象(list)

def func1(a):
    a[0] = 'new-value'     # 'a' references a mutable list
    a[1] = a[1] + 1        # changes a shared object


3) 通过字典(dict)

def func3(args):
    args['a'] = 'new-value'     # args is a mutable dictionary
    args['b'] = args['b'] + 1   # change it in-place


4)通过类的对象

class callByRef:
    def __init__(self, **args):
        for (key, value) in args.items()://args是个dict
            setattr(self, key, value)//相当于 self.key=value

def func4(args):
    args.a = 'new-value'        # args is a mutable callByRef
    args.b = args.b + 1         # change object in-place

args = callByRef(a='old-value', b=99)
func4(args)
print args.a, args.b
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: