首页 > 解决方案 > 如何访问嵌套函数中的实例?

问题描述

我试图访问嵌套函数中的值实例。不知道该怎么做。任何帮助,将不胜感激。谢谢

def on_pre_enter(self, *args):
    notifications_screen = self.manager.get_screen('notif')
    def listener(event):
        print(event.event_type)  # can be 'put' or 'patch'
        print(event.path)  # relative to the reference, it seems
        print(event.data)  # new data at /reference/event.path. None if deleted
        notifications = event.data
        if notifications.items() == None:
            return
        else:
            for key, value in notifications.items():
                print()
                notifications_screen.notificationslist.adapter.data.extend([value])

标签: pythonkivy

解决方案


如果您使用的是 python3,您可以在内部函数中声明value为变量。nonlocal

请参阅Python 非本地关键字

def myfunc1():
  x = "John"  # assign x to some dummy variable to be overwritten
  def myfunc2():
    nonlocal x
    x = "hello"
  myfunc2()
  return x

print(myfunc1())

推荐阅读