【问题标题】:Changing the local variable of a function from within another function that is defined in said function.. Python从在所述函数中定义的另一个函数中更改函数的局部变量.. Python
【发布时间】:2012-07-05 11:07:26
【问题描述】:

有没有办法从函数中定义的函数访问函数的局部变量? 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))

【问题讨论】:

  • 访问,更不用说在另一个范围内更改变量了,这几乎不是一个好主意。你能解释一下你的代码应该做什么吗?肯定有更好的方法。
  • @thg435,通常它对闭包很有意义。这就是为什么将 nonlocal 添加到 Python3 中的原因

标签: python function variables global local


【解决方案1】:

在 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))

【讨论】:

  • 谢谢!!我真的很感激。
  • @KingJames 更多python 2.x选项,可以看一些解决方案here
  • 有趣的解决方案!我可能倾向于在第二个版本中将caps 设为“私有”变量——cap_sentence._caps。
【解决方案2】:

虽然使用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.')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2019-04-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多