簡體   English   中英

完全覆蓋繼承的 __init__ Class Python 3

[英]Totally override __init__ in inherited Class Python 3

我有 class Game和 class RecentGame繼承自 class Game 我不需要 class RecentGame中的__init__與 class Game__init__有任何共同之處,所以我沒有使用super() function。但我確實需要這個 inheritance,因為我想使用class Game PyCharm 將此標記為警告,我想知道如何正確執行此操作,以免引起任何警告。 也許我一開始就做錯了?

這是我的代碼:

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 給我的警告:

錯過了對 super class 的 __init__ 的調用

編輯: class Game和 class RecentGame都具有相同的self屬性: dota_idinfodetailed_info 但是他們使用不同的方式獲得他們的價值。 class Game通過其 id 獲取游戲信息,而 class RecentGame通過他的dota_id獲取最后一名玩家的游戲信息。 所以它們基本上是一樣的,唯一的區別在於語義以及它們獲取infodetailed_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

像這樣:

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

我要離開游戲作為練習......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM