Skip to main content
 首页 » 编程设计

python之如何在没有全局, self 的情况下在python中保留每个函数调用中的值

2024年10月25日9daizhj

这个问题在面试中被问到, 定义应满足 3 种情况的函数

case 1:set initial balance 
case 2:deduct the amount and return balance 
case 3:should add amount to balance and return current balance  

条件: 1.不要使用全局变量 2.不要使用self(意味着没有类) 3.不要使用文件或类似的东西

所以我定义了这样的函数,

def fun1(amt,reset=None): 
    if reset: 
            fun1.balance = reset 
    fun1.balance = fun1.balance-amt 
    return fun1.balance 
 
print fun1(0,500)#will set balance 500 
print fun1(200) #will deduct amount 200 and return balance 300 
print fun1(0,400)#should add 400 to balance and return 700 

所以我想在每次函数调用时保留余额值 在上述情况下 乐趣 1(0,500) fun1(200) 运作良好 但是如何将代码修改为第三种情况 fun1(0,400) 返回 true 结果

卡在第三种情况下会更新余额...

请您参考如下方法:

你快到了。对于金额,使用负数进行扣除,使用正数进行添加。也可以使用零来查询余额:

def transact(amount, reset=None): 
    if reset: 
        transact.balance = reset 
    transact.balance = transact.balance + amount 
    return transact.balance 
 
print transact(0, 500) # will set balance 500 
print transact(-200)   # will deduct amount 200 and return balance 300 
print transact(400)    # add 400 to make 700 

我不确定这是否是面试官的想法,但它确实有效。