Home > Net >  Totally override __init__ in inherited Class Python 3
Totally override __init__ in inherited Class Python 3

Time:10-11

I have class Game and class RecentGame that is inherited from the class Game. I don't need my __init__ in the class RecentGame to have anything in common with the class Game's __init__, so I haven't used the super() function. But I do need this inheritance since I want to use methods of the class Game. PyCharm marks this as a warning and I want to know how to do it properly so it won't cause any warnings. Maybe I am doing it wrong at the first place?

Here's my code:

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()

This is the warning that PyCharm gives me:

Call to __init__ of super class is missed

EDIT: The class Game and the class RecentGame both have the same self attributes: dota_id, info, detailed_info. But they get their values using different ways. The class Game gets game info by its id while the class RecentGame gets info of the last player's game by his dota_id. So they are basically the same, the only difference is in semantic and in the ways they get their info and detailed_info. All needed methods are the same.

EDIT 2: Here's my Game __init__() method:

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

CodePudding user response:

Like this:

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

I'm leaving Game as an exercise...

  • Related