这背后的想法是,简单地说,我希望:
def test (a,b):
a += b
return a
>>>test(0,1)
>>>1
因此它记录a = 1,并将其保存为a的新参数。因此,如果我再次返回此函数并再次运行它,结果应为2。 另外我想知道,有没有办法检查参数的内容?关于noob问题的道歉,我真的开始学习python。
谢谢!
答案 0 :(得分:2)
在大多数语言中,函数的参数是局部变量,因此它们不存在于函数定义之外。
无法访问a
之外的b
或test
您想要做的是以下
def test(b):
return a + b
#create a global variable `a`
a = 0
#update global a
a = test(1)
或者:
def test(lst, b):
#we can update a list by changing the values at indices
lst[0] += b
#initialize accumulator as list index 0
lst = [0]
test(lst, b)
第二种方法有效,因为列表包含指向其值的指针,因此当在lst
中生成局部变量test
时,它具有与第一个元素相同的指针。当我们更改它指向的值时,该值将在原始列表中更改。
答案 1 :(得分:1)
首先:关于本地范围的变量(也不是很多语言如何),这不是Python的“工作原理”,如果您正在考虑将其用于严肃的应用程序,那么您可能需要重新评估
那就是说...你可以利用(读取:滥用)mutable defaults来实现这一目的,而无需在全局命名空间中放置变量。类似的东西:
def fn(a=0, b=0, *, storage={}):
if not storage:
storage.update(locals())
storage['a'] += b
return storage['a']
>>> fn(0, 1)
1
>>> fn(20, 1) # value of a no longer matters
2
>>> fn(b=3)
5
答案 2 :(得分:0)
使用decorator执行此操作,因为这只是一个演示,如果您愿意,还可以存储数据库或文件:
def store_a(func):
record_a = None
def wrap(**kwargs):
nonlocal record_a
a = kwargs.get('a', None)
b = kwargs.get('b', 0)
if a is not None:
record_a = a
record_a = func(record_a, b)
return record_a
return wrap
@store_a
def test(a=None, b=None):
if a is None:
a = 0
a += b
return a
print(test(a=0, b=1))
print(test(b=2))
print(test(b=3))
你可以获得1,3,6的结果