位置参数跟在关键字参数之后,不知道如何解决这个问题

Positional argument follows keyword argument, not sure how to resolve this

如何修复此错误?

代码:

import pandas as pd 
import seaborn as sns

api_key = 'API_KEY'
channel_id = 'CHANNEL_ID'

youtube = build('youtube','v3', developerKey=api_key)


def get_channel_stats (youtube, channel_id):
    request = youtube.channels().list(
            part= 'snippet','contentDetails','statistics',id=channel_id)
    response = request.execute()
    return response

错误信息:

SyntaxError: positional argument follows keyword argument

如何避免此错误?我在某个地方犯了一个愚蠢的错误,但不确定如何解决。

假设 youtube.channels().list() 的其余参数顺序正确,您只需要将 part = 'snippet' 移过去即可。解析器希望首先找到所有位置参数(未指定参数名称的参数),因此任何具有 <name>= 语法的参数都必须位于末尾。

原因是许多函数接受 *args**kwargs,它们的意义在于允许任意数量的参数。确保未命名参数被分配到正确位置的唯一方法是严格控制它们在函数调用中的顺序和位置。

import pandas as pd 
import seaborn as sns

api_key = 'API_KEY'
channel_id = 'CHANNEL_ID'

youtube = build('youtube','v3', developerKey=api_key)


def get_channel_stats (youtube, channel_id):
    request = youtube.channels().list(
            'contentDetails','statistics', part= 'snippet', id=channel_id)
    response = request.execute()
    return response

您的代码看起来不错,您只需要更改发送零件参数的方式即可。

您需要一个逗号分隔的字符串,而不是多个由逗号分隔的字符串。

import pandas as pd 
import seaborn as sns

api_key = 'API_KEY'
channel_id = 'CHANNEL_ID'

youtube = build('youtube','v3', developerKey=api_key)


def get_channel_stats (youtube, channel_id):
    request = youtube.channels().list(
            part='snippet,contentDetails,statistics', id=channel_id)
    response = request.execute()
    return response

实际上,当您在调用函数时混合使用关键字和位置参数时,python 中会出现此错误。strong text

您必须以所有位置参数在序列中的任何关键字参数之前首先出现的方式调用函数。

您可以通过更新下面的函数 get_channel_stats 来解决它:

def get_channel_stats (youtube, channel_id):
request = youtube.channels().list(
        'contentDetails','statistics', part= 'snippet', id=channel_id)
response = request.execute()
return response

希望它能解决问题。