Hi,

regenerate the whole object instead of a reset?

cheers,



On Saturday, May 25, 2019, Irv Kalb <i...@furrypants.com> wrote:

> Hi,
>
> I am teaching an Python object-oriented programming class based on my own
> materials.  I am using Pygame to explain many OOP concepts.  So far its
> going very well.
>
> I have built many small games as examples, but I keep running into a
> design dilemma.  I will often have a class, where I have an instance
> variable (I know it should be called an attribute!), and I want to be able
> to give it a starting value, but I also want to be able to reset it to the
> same value if the game is played more than once.  As a trivial example,
> here is the start of a Game class, that keeps track of the score of the
> game:
>
> class Game:
>     def __init__(self):
>         self.score = 0
>
>     def reset(self):
>          self.score = 0
>
> My main code instantiates a Game object and the game plays.  If the user
> wants to start the game over, I call the reset method.  There are two
> different problems with this approach:
>
>   1) I am duplicating code.  This gets nasty when I have lots of instance
> variables to reset.
>   2) Any time I want to change the "starting" value, I must make the
> identical change in both methods.
>
> The obvious solution is to have the __init__ method call the reset method:
>
> class Game:
>     def __init__(self):
>          self.reset()
>
>     def reset(self):
>           self.score = 0
>
> That does work fine and I like it.  But it breaks a general rule that you
> should declare all instance variables in the __init__ method.  I use
> PyCharm for the development of these games, and the "linter" (over the
> right side scroll bar) always flags this as a warning that a variable like
> this is not defined in my __init__ method.
>
> I'm looking for a general solution that solves this.  The best I've come
> up with so far is to do something like this for each instance variable:
>
> class Game:
>     def __init__(self):
>          self.score = None  # create the variable here, but only assign it
> a value in the reset method below
>          self.reset()
>
>     def reset(self):
>           self.score = 0  # Supply the actual start value here.
>
> Anyone have any other suggestions for how to do this cleanly?
>
> Thanks,
>
> Irv

Reply via email to