2012-07-05 101 views
2

有没有办法从函数中定义函数的局部变量? Y是一个带有字符串的元组,我想要满足一个条件时的任何大写字母,以保持与y中下一个项目的下一次调用相同。我试图使用内置函数全局,但我想这只适用于全局。在函数中定义的另一个函数中更改函数的局部变量.. Python

def cap_sentence(y): 
    caps = "on" 
    def func(x): 
     if caps == "on" 
      caps = "off" 
      return x.capitalize() 
     elif "." in x: 
      caps = "on" 
    return tuple(map(func, y)) 
+2

访问,更不用说在另一个范围内更改变量几乎不是一个好主意。你能解释一下你的代码应该做什么吗?肯定有更好的方法。 – georg 2012-07-05 11:15:01

+1

@ thg435,通常对于关闭有意义。这就是为什么nonlocal被添加到Python3 – 2012-07-05 11:30:37

回答

7

使用nonlocal在Python 3.X:

def cap_sentence(y): 
    caps = "on" 

    def func(x): 
     nonlocal caps 
     if caps == "on": 
      caps = "off" 
      return x.capitalize() 
     elif "." in x: 
      caps = "on" 

    return tuple(map(func, y)) 

在Python 2.7版:

def cap_sentence(y): 
    cap_sentence.caps = "on" 

    def func(x): 
     if cap_sentence.caps == "on": 
      cap_sentence.caps = "off" 
      return x.capitalize() 
     elif "." in x: 
      cap_sentence.caps = "on" 

    return tuple(map(func, y)) 
+0

谢谢!对此,我真的非常感激。 – 2012-07-05 11:17:03

+0

@KingJames更多'python 2.x'选项,你可以看到一些解决方案[here](http://goo.gl/jYhW9) – 2012-07-05 11:19:11

+0

有趣的解决方案!我可能会倾向于在第二个版本中将cap设置为“私有”变量 - cap_sentence._caps。 – senderle 2012-07-05 11:37:41

0

虽然使用nonlocal是直接回答你的问题,我建议你考虑在这里使用可调用的类。这样可以避免每次调用cap_sentence时重新定义一个函数,并且它以更明显的方式处理状态(无论如何)。我冒昧地在最后添加return语句,以便您不会得到一串None值。

class _CapSentence(object): 
    def __init__(self): 
     self.caps = 'on' 
    def capitalize(self, x): 
     if self.caps == 'on': 
      self.caps = 'off' 
      return x.capitalize() 
     elif '.' in x: 
      self.caps = 'on' 
     return x 
    def __call__(self, y): 
     return tuple(map(self.capitalize, y)) 

cap_sentence = _CapSentence() 

print cap_sentence("my feet are cold. my toes are sandwiches.".split()) 

# output: ('My', 'feet', 'are', 'cold.', 'My', 'toes', 'are', 'sandwiches.') 
相关问题