有没有办法从所述函数中定义的函数访问函数的局部变量? Y是一个带字符串的元组,我希望在条件满足时变为任何上限,以便在y中的下一个项目的下一个调用中保持相同。我试图使用内置函数global,但我想这只适用于全局变量。
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))
答案 0 :(得分:7)
在Python 3.x中使用nonlocal
:
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))
答案 1 :(得分:0)
尽管使用nonlocal
是您问题的直接答案,但我建议您考虑在此处使用可调用类。这避免了每次调用cap_sentence
时重新定义函数,并且它以更明显的方式处理状态(无论如何)。我已经冒昧地在最后添加一个返回声明,这样你就不会获得一串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.')