[Tutor] When to use classes

Cameron Simpson cs at zip.com.au
Wed Apr 9 13:25:14 CEST 2014

On 08Apr2014 22:58, Ni hung <niihung at gmail.com> wrote:
> I am learning programming using python. I think of solving a problem using
> functions and for this reason all/most of my code consists of functions and
> no classes.  I have some understanding of classes/Object Oriented
> Programming. I can write simple classes but I do not understand when to use
> classes.

Loosely speaking, you can usefully make a class when there is a
particular type of object on which you are make an assortedment of

For example, if you have several functions looking like this:

  def modify_thing1(obj1, ...):

  def add_something(obj1, ...):

and so on, where obj1 is always the same kind of thing, representing
some well define idea you have when writing the code.

In that circumstance you might make a class looking like this:

  class ObjName(object):

    def __init__(self):
      # "self" here is an "obj1" as used above
      # set whatever attributes an "obj1" should have to start with
      # you can pass in some of those values as parameters to the __init__ function

    def modify(self, ...):
      # this is the same as "modify_thing1(obj1, ...)" earlier
      # using "self" as "obj1"

    def add(self, ...):
      # this is the same as "add_something(obj1, ...)" earlier

Then your code looks like:

  obj1 = ObjName()

or what have you.

This has several advantages:

  - all the code that affects this kind of object is in one place

  - you can remove all the specifics of how things are done from the main
    code and keep them inside the class methods.
    This makes the main code more readable (if you pick good method names)
    and shorter (also more readable, usually).

  - later, if need be, you can change the inner workings of how
    ObjNames work without changing the main code, or at least not
    much - sometimes not at all

Anyway, that's an ok rule of thumb for when to make a class: when
you have a bunch of operations to do to one type of thing.

Cameron Simpson <cs at zip.com.au>

More information about the Tutor mailing list