【问题标题】:Returning a list from function从函数返回列表
【发布时间】:2019-05-20 21:06:28
【问题描述】:

我知道,这个问题很愚蠢,而且很容易在互联网上搜索到。 我做到了,但这对我没有帮助。 我正在使用适用于 Python (3.7.1) 的 Google Calendar API

from dateutil.parser import parse as dtparse
from datetime import datetime as dt
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'

start = '2018-12-26T10:00:00+01:00'   # Let's say your start value returns this as 'str'
tmfmt = '%d %B, %H:%M %p'


class Calendar():

    def getEvents(self):
        """Shows basic usage of the Google Calendar API.
        Prints the start and name of the next 10 events on the user's calendar.
        """
        # The file token.json stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        store = file.Storage('token.json')
        creds = store.get()
        if not creds or creds.invalid:
            flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
            creds = tools.run_flow(flow, store)
        service = build('calendar', 'v3', http=creds.authorize(Http()))

        # Call the Calendar API
        now = dt.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
        events_result = service.events().list(calendarId='primary', timeMin=now,
                                              maxResults=10, singleEvents=True,
                                              orderBy='startTime').execute()
        events = events_result.get('items', [])
        if not events:
            print('No upcoming events found.')
        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            stime = dt.strftime(dtparse(start), format=tmfmt)
            items = str(stime + event['summary'])
            print(items)
            return items

"""
 Tried aswell   str1 = ''.join(str(e) for e in items)
                return str1
"""


    def Events(self):
        print(self.getEvents())


x = Calendar()
x.Events()

我对其进行了修改,以便以人类可读的日期格式返回事件。 无论如何,当我在getEvents()print(stime + event['summary']) 时,我得到一个正常的输出.. 当我尝试在另一个函数中打印它时(最后它应该显示在一个 tkinter 标签中),它要么不起作用,要么打印第一个项目,或者最后一个......

这是如何实现的?

【问题讨论】:

  • 您应该显示实际和预期的输出,以使读者更清楚。无论如何,我可以看到您的代码在循环中包含一个return。这意味着该函数将在第一次迭代结束时返回。真的是你想要的吗?
  • 嗯,如果有的话,我需要它来退回物品。我可以把它搬出去,但我看不出它对我的问题会有什么不同
  • 我不明白为什么你看不到它会带来什么不同。试试看。

标签: python list function return google-calendar-api


【解决方案1】:

返回一个列表是通过字面上返回一个列表对象来实现的,而不是多次调用return。

确实,您的函数将在第一次遇到 return 语句时退出。例如:

>>> def func():
...     return 1
...     return 2
...     return 3
... 
>>> func()
1

我们没有得到[1, 2, 3] 的列表 - 我们以遇到的第一个返回返回的值退出。

具体来说,你有一个循环内的返回。这将导致函数在此循环的第一次迭代中退出。

您的事件循环可能希望看起来像这样:

ret = []
for event in events:
    # ... snip...
    ret.append(items)
return ret

您可能也想考虑重命名一些变量 - 例如,items 仅指单个项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2017-06-21
    • 1970-01-01
    相关资源
    最近更新 更多