+ 1

Default Argument not updated? (Python)

How can one modify this code so that the default argument changes based on value of variable i instead of copy? a=1 def func(n=a): print(n) a+=1 func()

28th Aug 2021, 1:30 AM
Edward Finkelstein
Edward Finkelstein - avatar
4 Respostas
+ 3
The best way to do that using function or object. eg. https://code.sololearn.com/cGiHZJK1G8cr/?ref=app
28th Aug 2021, 8:50 AM
Sousou
Sousou - avatar
+ 2
I think you'd have to use a class class Foo: a = 1 def __init__(self, n=a): self.n = n def func(self): print(self.n) my_var = Foo() my_var.func() # output 1
28th Aug 2021, 1:35 AM
Slick
Slick - avatar
+ 1
Delicate Cat In the code, incrementing the variable a to 2 does not change the default argument in the function func to 2. I want to know if there is a clean way to have the default argument in func get updated along with the variable a
28th Aug 2021, 5:08 AM
Edward Finkelstein
Edward Finkelstein - avatar
0
You set the new value for 'a' but it doesnt update the value of 'a' in the function unless you explicitly update it by passing an updated argument a = 1 def func(n=a): print(n) a += 1 func(a)
28th Aug 2021, 3:14 AM
Sacar
Sacar - avatar