[Tutor] creating classes while coding

Steven D'Aprano steve at pearwood.info
Mon Feb 21 12:49:04 CET 2011


Bill Allen wrote:
> That raises my next question.   Under what sort of programming circumstances
> does it make sense?

"It" being object oriented programming.

OO is good for encapsulation and code-reuse. One good sign you should 
consider a class is if you start building up many global variables. 
Instead of:


spam = 1
ham = 2
eggs = 3


def cook_spam():
     pass

def slice_ham():
     pass

def scramble_eggs():
     pass


there may be something to say for putting those related functions into a 
class:


class Breakfast:
     spam = 1
     ham = 2
     eggs = 3

     def cook_spam(self):
         pass

     def slice_ham(self):
         pass

     def scramble_eggs(self):
         pass



This then allows you to have two Breakfasts, each one of which could 
modify their own copies of spam, ham and eggs without effecting the other.



-- 
Steven


More information about the Tutor mailing list