简体   繁体   中英

Redefine Class Instances in Python

I am migrating a project I have from being littered with globals variables to actually have a structure defined by classes defined in a separate module. This is my first time really using OOP so want to understand if it is safe to re-define an instance of a Class or if my code is missing something.

At the top of my code, I import my module -

import NHLGameEvents
config = configparser.ConfigParser()
config.read('config.ini')

TEAM_BOT = config['DEFAULT']['TEAM_NAME']

I then build two Team objects (defined in my NHLGameEvents module).

game_today, game_info = is_game_today(get_team(TEAM_BOT))

awayteam_info = game_info["teams"]["away"]["team"]
awayteamobj_name = awayteam_info["name"]
awayteamobj_shortname = awayteam_info["teamName"]
awayteamobj_tri = awayteam_info["abbreviation"]
away_team_obj = NHLGameEvents.Team(
    awayteamobj_name, awayteamobj_shortname, awayteamobj_tri, "away")
game_obj.register_team(away_team_obj, "away")

hometeam_info = game_info["teams"]["home"]["team"]
hometeamobj_name = hometeam_info["name"]
hometeamobj_shortname = hometeam_info["teamName"]
hometeamobj_tri = hometeam_info["abbreviation"]
home_team_obj = NHLGameEvents.Team(
    hometeamobj_name, hometeamobj_shortname, hometeamobj_tri, "home")
game_obj.register_team(home_team_obj, "home")

home_team_obj.preferred = bool(home_team_obj.team_name == TEAM_BOT)
away_team_obj.preferred = bool(away_team_obj.team_name == TEAM_BOT)

In some instances, I want to reference these Team objects as preferred and other as opposed to home / away so I use a method defined in my Game class to retrieve that. Since my Game object knows about both of my Teams , the method in my Game class that returns this Tuple is -

def register_team(self, team, key):
    """Registers a team to the instance of the Game."""

    if key not in ('home', 'away'):
        raise AttributeError(
            "Key '{}' is not valid - Team key can only be home or away.".format(key))

    if len(self.teams) > 1:
        raise ValueError(
            "Too many teams! Cannot register {} for {}".format(team, self))
    self.teams[key] = team
    team.game = self
    team.tv_channel = self.broadcasts[key]


def get_preferred_team(self):
    """Returns a Tuple of team objects of the preferred & other teams."""
    if self.teams["home"].preferred is True:
        return (self.teams["home"], self.teams["away"])

    return (self.teams["away"], self.teams["home"])

I can then retrieve that information from anywhere in my script. preferred_team_obj, other_team_obj = game_obj.get_preferred_team()

Is it safe to redefine these class instances (ex - home_team_obj also known as preferred_team_obj ) or should I just use an if statement whenever I want to reference these, such as -

if home_team_obj.preferred:
    # Do something with home_team_obj
else:
    # Do something with away_team_obj

Just as a follow up to this question, it seems that is totally safe to refer to assign an object to another name for use later in the code with no issues (as per the example below).

preferred_team = game.preferred_team
preferred_homeaway = preferred_team.home_away
on_ice = json_feed["liveData"]["boxscore"]["teams"][preferred_homeaway]["onIce"]
players = json_feed["gameData"]["players"]
if recent_event(play):
    get_lineup(game, event_period, on_ice, players)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM