I'd like do something like this:
f = lambda x: None
x = [f]
def f(n):
return n
print x[0](2)
Expected result is 2
, but it's actually None
.
I know it's possible to solve with classes, but can it be done without them?
I'd like do something like this:
f = lambda x: None
x = [f]
def f(n):
return n
print x[0](2)
Expected result is 2
, but it's actually None
.
I know it's possible to solve with classes, but can it be done without them?
Here you are creating an anonymous function and adding it to a list. Now there are two references pointing to the lambda. Although you define another function with same name f, this does not effect the reference in the list as it points to the lambda.
What are you trying to achieve here?
You are storing a reference to the function in the list x not its name.
you could do something like
f = lambda x: None
x = ['f']
def f(n):
return n
print globals()[x[0]](2)
but this is kinda "bad". Maybe you could explain why you are trying to do that and we can find you a better way.
You can set f as a global variable:
global f
f = lambda x: x+1
x = f
x(1)
OUT: 2
f = lambda x: x+2
x = f
x(1)
OUT: 3
Hmm, that's easy (:. Function is a object as anything else. What about doing
x = [f]
or
x[0] = f
after you redefined f?