繁体   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