蟒蛇:我怎么调用一个函数不改变参数? [英] python: how do I call a function without changing an argument?

查看:88
本文介绍了蟒蛇:我怎么调用一个函数不改变参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个函数:

def foo(self, a, b):
    c = a + b
    return c

我怎么能调用foo不会在功能改变C吗?所以我们可以说我调用foo在其它功能:

How can I call foo without changing c in the function? So let's say I call foo in another function:

def bar(self):
    z = self.foo(2, 4)
    return (z)

然后我想在一个单独的功能再打电话富,但我想从时间栏被名为c。

and then I want to call foo again in a separate function, but I want c from the time 'bar' was called.

def baz(self):
    self.foo(?, ?) # trying to just get c, without any changes.

基本上,我试图保持一个账户类,这样其他类可以访问相同的帐户;只是一个简单的平衡,加减钱。

Basically, i'm trying to keep an account in class such that other classes can have access to the same account; just a simple balance, adding and subtracting money.

感谢。

推荐答案

我已经采取了什么罗汉提供了一个答案,并拿出以下。它似乎工作,虽然有可能实现这个美好/ preferred方式。

I've taken what Rohan provided for an answer and come up with the following. It seems to work, although there may be a better/preferred way to accomplish this.

以下code可让我继续跟踪多个类和方法的帐户余额。

The following code allows me to keep track an account balance across multiple classes and methods.

import os

class Foo():
    def __init__(self):
        self.stored_end = 0

    def account(self, a, b):
        c = float(a) + b
        print a
        print b
        print c
        self.stored_end = c
        print self.stored_end

    def testy(self, q, v):
        print "\n"
        print " _ " * 10
        z = float(q) + v
        print self.stored_end   
        self.stored_end = self.stored_end + z
        print " _ " * 10
        print self.stored_end

class Bar():
    def __init__(self):
        pass

    def zippy(self, a, b):
        print " _ " * 10
        print "this is zippy"
        foo.testy(a, b)

class Baz():
    def __init__(self):
        pass

    def cracky(self, g, m):
        y = g + m
        print " _ " * 10
        print "calling stored_end"
        foo.stored_end = foo.stored_end + y
        print " _ " * 10
        print "this is cracky"
        print "y = %r" % y
        print foo.stored_end    

os.system("clear")      
foo = Foo()
foo.account(5, 11)
foo.testy(100, 100)
bar = Bar()
bar.zippy(10, 100)
baz = Baz()
baz.cracky(1000, 1)

这篇关于蟒蛇:我怎么调用一个函数不改变参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆