Python类实例化:已加self仍报get_access_token()参数不匹配
问题排查与代码修正
触发报错的核心原因
- 你遇到的
TypeError: get_access_token() takes 0 positional arguments but 1 was given,本质是没有严格遵循Python类实例方法的参数规则:- 所有绑定到类实例的普通方法,必须把
self作为第一个形参写在参数列表最开头 - 当你用
实例.方法()的形式调用方法时,Python会自动把当前实例作为第一个位置参数传入方法,不需要手动传递
- 所有绑定到类实例的普通方法,必须把
- 从你贴的代码能看到明显的参数顺序错误:
def get_match_details(match_id, self):把self放在了第二个参数位置def get_match_details_in_range(match_id, match_id_upper_bound, self):把self放在了最后一个参数位置- 这种写法下,Python自动传入的实例对象会被匹配到第一个业务参数
match_id上,你传入的业务参数值反而会被当成self,方法内部访问self.url、self.requests时自然读不到正确的实例属性
- 至于当前运行触发的
get_access_token报错,大概率是你本地实际运行的代码版本和贴出的版本不一致:要么get_access_token漏写了self参数,要么同样把self放到了参数列表靠后的位置。如果真按你贴的写法把self放在get_access_token的第一个参数位置,是不会触发这个参数数量不匹配的报错的。
其他需要修正的细节问题
- 类内部的
import requests, time, pandas as pd属于类级别导入,虽然能运行,但不符合常规Python编码规范,建议移到类定义的外层 get_access_token里的file.close没有加括号,实际不会执行关闭操作——不过你已经用了with上下文管理器,文件会自动安全关闭,这行冗余代码可以直接删掉initialize_items方法里重复调用了response.json(),可以把第一次解析的结果存为变量复用,减少不必要的重复解析- 方法末尾无意义的
pass占位符可以全部删掉,函数体已经有实际执行逻辑时,pass没有任何作用
修正后的可运行代码
### API MANAGER ### import requests import time import pandas as pd class api_manager(): def __init__(self, api_identifier = 1): test_api_url = "https://api.steampowered.com/IDOTA2Match_570/" live_api_url = "https://api.steampowered.com/IDOTA2Match_205790/" self.heroes = [] self.items = [] self.token = '' self.url = "" if api_identifier == 1: self.url = live_api_url else: self.url = test_api_url self.get_access_token() self.initialize_heroes() self.initialize_items() def get_access_token(self): with open("conf/access.config") as file: self.token = file.read().split(":")[1] def initialize_heroes(self): response = requests.get(self.url + "GetHeroes/v1/?format=JSON&language=en_us&key=" + self.token) hero_list = response.json() for hero_id in range(len(hero_list['result']['heroes'])): self.heroes.append([ hero_list['result']['heroes'][hero_id]['id'], hero_list['result']['heroes'][hero_id]['localized_name'], hero_list['result']['heroes'][hero_id]['name'].replace('npc_dota_hero_', "").replace("_", " ") ]) self.heroes.sort() heroes_df = pd.DataFrame(self.heroes, columns=["ID", "Hero", "Hero Tag"]) pd.set_option('display.max_colwidth', -1) def initialize_items(self): response = requests.get(self.url + "GetGameItems/v1/?format=JSON&language=en_us&key=" + self.token) item_list = response.json() for item_id in range(len(item_list['result']['items'])): self.items.append([ item_list['result']['items'][item_id]['id'], item_list['result']['items'][item_id]['localized_name'], item_list['result']['items'][item_id]['name'] ]) self.items.sort() items_df = pd.DataFrame(self.items, columns=["ID", "Item", "Item Tag"]) pd.set_option('display.max_colwidth', -1) # 修正self参数位置,放到参数列表首位 def get_match_details(self, match_id): response = requests.get(self.url + "GetMatchDetails/V001/?format=JSON&language=en_us&key=" + self.token + "&match_id=" + str(match_id)) print(response.json()) # 修正self参数位置,放到参数列表首位 def get_match_details_in_range(self, match_id, match_id_upper_bound): for next_match_id in range(match_id, match_id_upper_bound): response = requests.get(self.url + "GetMatchDetails/V001/?format=JSON&language=en_us&key=" + self.token + "&match_id=" + str(next_match_id)) print(response.json()) time.sleep(1.05)
常见问题说明
- 你之前遇到的“url未初始化报错”,本质就是
self参数错位传递后,变量根本没有指向类实例,自然读不到__init__方法里初始化的self.url值,和url本身有没有初始化没有关系 - 修正参数顺序后,方法内部的
self会正确指向当前实例,__init__里设置的url、token、英雄列表等属性都能正常访问,不会再出现属性找不到的问题
内容的提问来源于stack exchange,提问作者Samaranth
相关产品推荐
相关产品推荐

