[Python] Copy attribute values in Python class [closed]

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am writing a function to pick an 'optimal' NHL Fantasy team. My function works as follows:

    1. identifies the worst player in the team,
    2. compares this player to a randomly selected player in the league,
    3. replaces the worst player if better
    4. repeat for given number of loops

    I first create an instance of a class and generate an initial team saved under self.init_team. At the start of the loop, I store the initial team as self.current_team, and then update the team if players are substituted. Finally, I store the best team as self.best_team.

    The function works fine, except that self.current_team overwrites self.init_team.

    Is there an easy way to copy self.init_team at the start of the function to store it for later while using the values to create a new instance? Or do I have to create a new instance using the same inputs in order to copy the attribute?

    Code

    self.init_team = SOME INITIAL TEAM
    self.current_team = self.init_team
    ...
    [running the loop]
    ...
    self.best_team = self.current_team.


    What I want

    self.init_team = SOME INITIAL TEAM
    self.best_team = BEST TEAM AFTER LOOP


    What I get

    self.init_team = BEST TEAM AFTER LOOP
    self.best_team = BEST TEAM AFTER LOOP

    Continue reading...

Compartilhe esta Página