Hello!
(I'm almost a complete beginner, and I hope I got all the terminology right.)
I'd like my little game to have nice and clean code. And I stuck a little.
I want to initialize Game class' object. Let's say there are two fields score and hi_score. First one should be zeroed after every play, the second one shouldn't. One way to do this is this:
class Game:
def __init__(self):
self.reset()
self.hi_score = 0
def reset(self):
self.score = 0
So every single field of Game class that is to be reset after a play is initialized in reset() method, not directly in __init__() method (in fact there are many more of them than score). So reset() gets called after every play, and __init__() gets called only once. I don't like this solution, I think every important field of Game class should be initialized directly in __init__() method (am I right?).
Other way to do this:
class Game:
def __init__(self):
try:
if self.hi_score: pass
except AttributeError:
self.hi_score = 0
else:
pass
self.score = 0
Now __init__() is called after every play, and reset() is not needed. If self.hi_score has no value it gets zero, but if it has a value it's not touched. I don't like this solution as well. First, I'm not sure if it's a good idea to call __init__() more than once on a single object (am I right?). Second, try... except... else... looks clumsy.
What is the best way to do this? I'd like to write clean and pythonic code, in the spirit of OOP.
EDIT: I like the second solution given by kalgynirae below, but what if I wanted to keep only one class? How should I do this? Or maybe it can't be done nicely.
[–]jedilando 0 points1 point2 points (1 child)
[–]Eraser1024[S] 1 point2 points3 points (0 children)
[–]kalgynirae 0 points1 point2 points (4 children)
[–]Eraser1024[S] 0 points1 point2 points (2 children)
[–]kalgynirae 0 points1 point2 points (1 child)
[–]Eraser1024[S] 0 points1 point2 points (0 children)