[英]How do I update function parameters based on input in python?
The idea behind this is, simply said, I want to have:这背后的想法是,简单地说,我想要:
def test (a,b):
a += b
return a
>>>test(0,1)
>>>1
So it records that a = 1, and saves it as its new parameter for a.所以它记录a = 1,并将其保存为a的新参数。 So if I return to this function again and run it again, the result should be 2. Also I was wondering, is there any way to check the contents of a parameter?所以如果我再次返回这个函数并再次运行它,结果应该是2。我也想知道,有没有办法检查参数的内容? Apologies about noob questions, I'm literally just starting to learn python.关于菜鸟问题的道歉,我真的只是开始学习python。
Thank you!谢谢!
In most languages, the parameters of a function are local variables, and as such they do not exist outside of the function definition.在大多数语言中,函数的参数是局部变量,因此它们不存在于函数定义之外。
it's impossible to access a
or b
outside of test
在test
之外无法访问a
或b
What you wanted to do was the following你想做的是以下
def test(b):
return a + b
#create a global variable `a`
a = 0
#update global a
a = test(1)
or alternatively:或者:
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)
The second method works because lists contain pointers to their values, so when a local variable lst
is made in test
it has the same pointer to the first element.第二种方法有效,因为列表包含指向它们的值的指针,所以当在test
创建局部变量lst
,它具有指向第一个元素的相同指针。 When we change the value it points to, the value will change in the original list.当我们改变它指向的值时,原始列表中的值也会改变。
First off: this isn't quite how Python 'works' with regard to locally-scoped variables (nor indeed how a lot of languages do) and if you're considering it for a serious application then you may have to reevaluate.首先:这并不是 Python 在局部范围变量方面的“工作原理”(实际上也不是很多语言的工作方式),如果您正在考虑将其用于严肃的应用程序,那么您可能需要重新评估。
That said... you can leverage (read: abuse) mutable defaults to this end, without placing variables in the global namespace.也就是说……您可以为此利用(阅读:滥用) 可变默认值,而无需在全局命名空间中放置变量。 Something like:类似的东西:
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
Using decorator to do this, for this is just a demo, if you like you can also store a in db or file:使用装饰器来做到这一点,因为这只是一个演示,如果你愿意,你也可以将 a 存储在 db 或文件中:
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))
and you can get 1, 3, 6 as result你可以得到 1, 3, 6 结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.