从函数返回列表

时间:2018-12-20 10:42:26

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

我知道,这个问题很愚蠢,可以在互联网上轻松搜索到。 我做到了,但这没有帮助我。 我正在使用适用于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()

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

这是如何实现的?

1 个答案:

答案 0 :(得分:2)

返回列表是通过从字面上返回列表对象而不是多次调用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仅指单个项目。