我有從 class 繼承的classGame和class 。我不需要 my in class與 class 's有任何共同之處,所以我沒有使用該功能。但我確實需要這種繼承,因為我想使用類的方法。PyCharm 將此標記為警告,我想知道如何正確執行此操作,以免引起任何警告。也許我一開始就做錯了?RecentGameGame__init__RecentGameGame__init__super()Game
這是我的代碼:
class RecentGame(Game):
def __init__(self, dota_id):
self.dota_id = dota_id
self.info = requests.get(OPENDOTA_API_URL f"players/{dota_id}/matches?limit=1").json()[0]
self.detailed_info = requests.get(f"http://api.opendota.com/api/matches/{self.info['match_id']}").json()
這是 PyCharm 給我的警告:
錯過了對超類的 __init__ 的呼叫
編輯:類Game和類RecentGame都具有相同的self屬性:dota_id, info, detailed_info. 但他們使用不同的方式獲得他們的價值觀。該類Game通過其 id 獲取游戲資訊,而該類RecentGame通過 his 獲取最后一個玩家的游戲資訊dota_id。所以它們基本上是相同的,唯一的區別在于語意和他們得到infoand的方式detailed_info。所有需要的方法都是一樣的。
編輯2:這是我的Game __init__()方法:
class Game:
def __init__(self, dota_id, game_id):
self.dota_id = dota_id
self.detailed_info = requests.get(f"http://api.opendota.com/api/matches/{game_id}").json()
is_in_game = False
for player in self.detailed_info['players']:
if player['account_id'] == dota_id:
is_in_game = True
break
if is_in_game:
temp = requests.get(f"https://api.opendota.com/api/players/{dota_id}/matches").json()
for match in temp:
if match['match_id'] == game_id:
self.info = match
break
else:
raise PlayerNotInGameException
uj5u.com熱心網友回復:
像這樣:
class BaseGame:
def __init__(self, dota_id, info, detailed_info):
self.dota_id = dota_id
self.info = info
self.detailed_info = detailed_info
# rest of old Game class elided
class RecentGame(BaseGame):
def __init__(self, dota_id):
info = requests.get(OPENDOTA_API_URL f"players/{dota_id}/matches?limit=1").json()[0]
detailed_info = requests.get(OPENDOTA_API_URL f"players/{dota_id}/matches?limit=1").json()[0]
super().__init__(dota_id, info, detailed_info)
# nothing else needed
我要離開游戲作為練習...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/513968.html
