[Tutor] Some question about OO practice

Alan Gauld alan.gauld at btinternet.com
Sun Nov 4 14:25:11 CET 2007

"John" <washakie at gmail.com> wrote

> I've now written my first set of Classes to do some fairly specific
> processing for work I do. I have a few questions.
> First, in looking through what I've done, I basically just 
> incorporated all
> my previous scripts into classes... they are still highly specific 
> to my
> application, though I did try to make them somewhat 'reusable' or 
> general.

That may be OK but without knowing more about what these
scripts do then its hard to say. Its possiblye that the scripts
are all of the same general nature and deal with comon data
elements or perform similar functions but with different
algorithms or data parameters. In those cases there are
probably ways to use abstract classes to create a  uniform
class framework that can then be specialised for each task.
But to know if that makes sense requires a lot more information
about the nature of the problem

Also, it depends a bit on how you implemented the classes.
If you literally just put

class foo:

at the top of the module and treated all variables as attributes
and converted all functions to methods then probably you
haven't gained much advantage.

> I guess, I'm writing because I'm wondering now what people think 
> about
> writing classes versus just using scripts for things that are so 
> specific.

The more specific the task the less useful clases will be. As the name
suggests classes are used for solving problems that can be classified,
wjhere the generic aspects can be captured in one place (a superclass)
and the specifics put someplace else (a subclass).

> One thing I am struggling with is how to assign *args and **kwargs 
> if they
> are passed, and how to ignore them if they are not... right now I do 
> this:
> def myfunc(self, *args,**kwargs):
>   a=self.a
>   b=self.b
>   kwa=self.kwa
>   kwb=self.kwb
>   try:
>        a=args[0]; b=args[1]
>        kwa=kwargs['a']
>         kwb=kwargs['b']
>   except: pass
> Where self.X is defined in the __init__ of the class. Is that 
> correct?

It should work although in my (limited) experience of using 
it is more common for them to be used in this way within the init()
itself rather than in another method. When you create an instance
you would pass all the attriubute data it needs to do its job. Once
instantiated the methods of the object should rarely need to
set lots of attributes to new values, maybe one or two but not
many. Typically that suggests that some other object is messing
with data that the instance should be managing itself!

But again without context its impossible to be definitive, there are
exceptions to every rule - especially in OOP! But the pattern would
generally raise alarm bells for me until I understood why it was that


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list