[Tutor] When to use classes
niihung at gmail.com
Thu Apr 10 07:42:48 CEST 2014
Thank you Alan, Dave and Cameron (and folks managing this email group)!
Your replies were very helpful.
On Wed, Apr 9, 2014 at 4:25 AM, Cameron Simpson <cs at zip.com.au> wrote:
> On 08Apr2014 22:58, Ni hung <niihung at gmail.com> wrote:
> > I am learning programming using python. I think of solving a problem
> > functions and for this reason all/most of my code consists of functions
> > no classes. I have some understanding of classes/Object Oriented
> > Programming. I can write simple classes but I do not understand when to
> > 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__
> 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>
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor