Sometimes you want different clients to be able to use your module with different settings so that they do not conflict with each other. For example, the Python random module provides many random number generation functions that are actually associated with the hidden instance method random . Most users do not care about which algorithm generates their random numbers, or other modules requesting random numbers will change the sequence. However, users who really care can get their own random object and generate sequences of random numbers that will not be affected by other modules requesting random numbers.
Sometimes, something global can now not always be global. For example, if you are working with planetary RTS, you might have the Planet class with one instance, because the battle only takes place on one planet. However, you do not want to exclude the possibility of creating something like Planetary Destruction, a battle that extends across all solar systems, and discarding asteroids in the form of a superweapon. If you get rid of the Planet class and execute its methods and attributes at the module level, it will be much more difficult to return and add more planets later.
Sometimes, it is more readable for objects to do things instead of modules. For example, suppose the joebob module defines two objects, evil_overlord_bob and good_guy_joe .
class Bob(object): def slaughter_everything(self): print "Muahahaha! Die for my amusement!" class Joe(object): def stop_bob(self): print "I won't let you hurt those innocents!" evil_overlord_bob = Bob() good_guy_joe = Joe()
Suppose Bob and Joe are very unique people. It is inconceivable that you want to create another object, similar to Bob or Joe. In this case, you can move slaughter_everything and stop_bob to the module level and completely get rid of the Bob and Joe classes and objects. However, then you will write
joebob.slaughter_everything() joebob.stop_bob()
Itβs much clearer what happens if you can say
evil_overlord_bob.slaughter_everything() good_guy_joe.stop_bob()
even if you never need to create a brother instance with the same evil brother greg_the_fleshripper .