2015-10-14 69 views
1

可以说我有一个函数,里面有一个可变的持续时间。是否有可能为python中的函数设置实例变量?

是否有任何方法可以在不调整任何参数的情况下在其他一些非功能函数外设置持续时间值?

+0

从'slowAction'或'make_slow'外面? – cdonts

+0

对不起,如果我不清楚。我想调整一个完全独立于我称之为函数的函数的值。 – swagbag

+0

恐怕这是不可能的。为什么你不能使用参数? – cdonts

回答

2

使用Python 3.x的你可以用nonlocal关键字

def make_slow(action): 
    slowDuration = None 

    def slowAction(self, colony): 
     nonlocal slowDuration 
     slowDuration = 10 # It is changing the variable from the scope above 

声明,如果你想从别的地方改变一个值,你不能返回值,尝试将global ...注意这可能会污染你当前的命名空间。

对于更pythonic的方法,你应该使用类似self.slowDuration。这就是对象的用途。

1

slowDurationslowAction函数的局部变量。局部变量的要点是它们只能在函数内部访问。

您应该更改slowAction函数,以便它使用另一个位置定义的slowDuration变量,例如作为make_slow显然属于的类的成员变量。

您还可以使slowAction成为覆盖__call__方法的类的实例。

>>> class Counter: 
...  def __init__(self): 
...   self.count = 0 
...  def __call__(self, delta): 
...   self.count += delta 
...   print(self.count) 
...  def set_count(self, c): 
...   self.count = c 
... 
>>> c = Counter() 
>>> c(1) 
1 
>>> c(3) 
4 
>>> c(3) 
7 
>>> c(3) 
10 
>>> c.set_count(42) 
>>> c(-2) 
40 

你也可以使用一些诡计使函数对象本身上可用的共享变量:

def makeCounter(): 
    counter = None 
    def counter_func(): 
     counter.count += 1 
     print(counter.count) 
    counter = counter_func 
    counter.count = 0 
    return counter 

,并使用它像这样:

>>> c = makeCounter() 
>>> c() 
1 
>>> c() 
2 
>>> c() 
3 
>>> c() 
4 
>>> c.count = 42 
>>> c() 
43 
>>> c() 
44 
>>> c() 
45 

但总的来说,“聪明“的代码应该避免,除非你有很好的理由使用它,因为它使得代码库变得更难理解。

相关问题