When is the best place to use a class in Python?

I am new to python and programming in general, so I will be very grateful for any clarifications on this.

For example, in the following code:

#Using a class class Monster(object): def __init__(self, level, damage, duration): print self self.level = level self.damage = damage self.duration = duration def fight(self): print self print "The monster level is ", self.level print "The monster damage is ", self.damage print "The attack duration is ", self.duration def sleep(self): print "The monster is tired and decides to rest." x = Monster(1, 2, 3) y = Monster(2, 3, 4) x.fight() y.fight() y.sleep() #just using a function def fight_func(level, damage, duration): print "The monster level is ", level print "The monster damage is ", damage print "The attack duration is ", duration fight_func(1, 2, 3) fight_func(5,3,4) 

A clean version of the function seems cleaner and gives the same result.

It is the main value of classes that you can create and call many methods on an object, for example. fight or sleep?

+8
function python oop class
source share
4 answers

Your example is pretty simplistic.

In a more complete example, a fight will not just display the current state - it will also change that state. Your monster may suffer, and this will change his points and morale. This state must be saved somewhere. If you use a class, it would be natural to add instance variables in order to maintain this state.

Using functions only, it would be harder to find a good place to store the state.

+11
source share

Your example is not particularly interesting - it just prints three numbers. You do not need classes or even a function (really) for this.

But if you ever need to write a program that should monitor two separate monsters at a time, know their health, distinguish their fighting abilities, and therefore you can see the value of encapsulating each of the monsters in a separate instance of the monster.

+2
source share

what about my monsters? he can fight with another monster! Presumably your functional monster cannot do this, -)

 class Monster(object): def __init__(self, level, damage, duration): self.level = level self.damage = damage self.duration = duration def fight(self, enemy): if not isinstance(enemy, Monster) : print "The enemy is not a monster, so I can't fight it." return None else : print "Starting fighting" print "My monster level is ", self.level print "My monster damage is ", self.damage print "My monster attack duration is ", self.duration print "The enemy level is ", enemy.level print "The enemy damage is ", enemy.damage print "The enemy attack duration is ", enemy.duration result_of_fight = 3.*(self.level - enemy.level) + \ 2.*(self.damage - enemy.damage) + \ 1.*(self.duration - enemy.duration) if result_of_fight > 0 : print "My monster wins the brutal battle" elif result_of_fight < 0 : print "My monster is defeated by the enemy" else : print "The two monsters both retreat for a draw" return result_of_fight def sleep(self, days): print "The monster is tired and decides to rest for %3d days" % days self.level += 3.0 * days self.damage += 2.0 * days self.duration += 2.0 * days x = Monster(1, 2, 3) y = Monster(2, 3, 4) x.fight(y) x.sleep(10) 

So:

 Starting fighting My monster level is 1 My monster damage is 2 My monster attack duration is 3 The enemy level is 2 The enemy damage is 3 The enemy attack duration is 4 My monster is defeated by the enemy The monster is tired and decides to rest for 10 days 
+2
source share

This is a more general answer than for your code, but classes are useful when you need to:

  • Securely share content through specific features .

    Classes offer encapsulation to avoid contaminating the global namespace with variables that need to be used for only a few functions. You do not want someone to use your code to overwrite a variable that all your functions use β€” you always want to be able to control access as much as possible.

    Classes can be created and have several independent copies of the same variable that are not shared, and very little code is required.

    They are suitable when you need to model interactions between a set of functions and variables with another set of functions and variables, i.e. when you need to model objects. Defining a class for one stateless function is essentially a waste of code.

  • Provide operator overload or define specific characteristics for certain types

    What does int , string and tuples do (can it be used as a key in a dictionary or inserted into set ), but list and dict are not?

    Answer: the base classes for these primitive types implement the __hash__ magic method , which allows the Python compiler to dynamically calculate the hash on at run time.

    Which allows the operator + to be overloaded, so that 5 + 2 = 7 for int , but 's' + 'a' = 'sa' for strings?

    Answer: the base classes for these types define their own __add__ method, which allows you to precisely determine how the addition is performed between the two members of your class.

    All custom classes can implement these methods. There are good precedents for them: the larger math libraries - numpy, scipy and pandas - make heavy use of operator overloading by defining these magic methods to provide you with useful objects for processing your data. Classes are the only way to implement these properties and properties in Python.

Classes do not exceed functions if the above conditions are not met.

Use the class to group meaningful functions and variables together in a smart way or to give your objects special properties. Everything else is redundant.

0
source share

All Articles