r/learnpython • u/rwmmir • Oct 07 '20
Classes in Python
Hey,
what is the best way to learn using classes in Python? Until now, I was using functions for almost every problem I had to solve, but I suppose it's more convenient to use classes when problems are more complex.
Thanks in advance!
324
Upvotes
3
u/fiddle_n Oct 08 '20
It's important to distinguish between "knowing when an enemy is dead", vs "removing an enemy from memory". Also, this is less about enemy instances, and more about the code that uses them.
If an enemy's life is below 0, then you can use this information to declare the enemy dead. Any time the player attempts a fight, they can perform this check, and if the health is below 0, then you know the enemy is dead and you do no further action with it. (In reality, you would probably have code to ensure health never actually drops below 0, and you might have a flag called
is_alivethat is set to False if health is 0, and then you check this flag rather than checking health directly, but the concept remains the same).delis used to remove objects from memory. You can use it to remove your enemy object from memory, but rarely is this the correct answer. The correct answer depends upon the situation in which the enemy objects are used.For example, If you know you only have a set number of enemies to deal with (e.g. exactly 100), you might just create them and not worry about the memory usage. But if you are always creating enemies, then this might not be viable and you might run out of memory after a while depending on the design of the game.
If, however, the game always has battles, but you only create three enemies at a time, you could have a function that represents a single battle, where you create three enemies. Then, when the battle ends, if you return from the function, the enemy objects will be removed from memory by Python's garbage collector as nothing is using them anymore.