Re-evaluating a var in python
Consider the following pseudo-code:
class Atrribute(object):
def __init__(self):
self.value = 0
def get():
self.value = random(10)
def func(var):
lambda var: return var+1
1) myFunc = func(Attribute().get())
2) myFunc()
3) myFunc()
Now, when I call myFunc() in line 2 I get a random value from 0 to 10 (plus one) which was produced by the get() function in Attribute. The problem is that when I call myFunc() in line 3, I get the same random value from line 2. Is there anyway I can开发者_JS百科 make python initiate the get() function again on line 3 to produce a new random value?
Meir
Yes, there is:
import random
class Attribute(object):
def __init__(self):
self.value = 0
def get(self):
self.value = random.random() * 10
return self.value
def func(fn):
return lambda: fn() + 1
att = Attribute()
myFunc = func(att.get)
print myFunc()
print myFunc()
In future, please make sure that any code that you post is free of syntax errors and actually does what you say it does.
How about:
def myFunc():
return random(10)
Your code (if written correctly and as I believe you intended it) would only call Attribute.get() once,, on lin 1. Then assigns the value returned to the variable 'myFunc'.
Try this instead:
class Atrribute(object):
def __init__(self):
self.value = 0
def get():
self.value = random(10)
def func(var):
return var+1
1) a = Attribute()
2) myFunc = a.get
3) func(myFunc)
4) func(myFunc)
精彩评论