[Tutor] Classes

Roeland Rengelink r.b.rigilink@chello.nl
Tue, 15 May 2001 09:51:52 +0200


Hi Tim,

"Timothy M. Brauch" wrote:
> 
> Right now in a program I am writing, I have one huge class that does many things.  I was thinking of
> breaking it up into smaller, specialized classes.  However, I have a dictionary that holds values
> that the functions need.  How can I have all my specialized classes read from and write to the same
> dictionary?  Can it be done?
> 

Sure, 

How about telling your instances what dictionary to use at instantiation
Something like:

class A:
    def __init__(self, dict):
        self.dictionary = dict

class B
    def __init__(self, dict):
        self.dictionary = dict

the_dict = {}
a = A(the_dict)
b = B(the_dict)

a and b are now using the same dictionary. Every modifiction made by a
will be visible to b. What I don't like about this solution is that I
have to tell everybody about this dictionary now. Moreover, the user
must now call some operations on a and other operations on b. A solution
might be:

class Facade:
    def __init__(self):
        the_dict = {}
        self.a = A(the_dict)
        self.b = B(the_dict)
    def func_0(self, arg1, arg2):
        self.a.func_0(self, arg1, arg2)
    def func_1(self, arg1, arg2, arg3):
        self.b.func_0(self, arg1, arg2, arg3)

The user just sees one class again

> A very simple example (my real code is fast approaching 750 lines):
> 
> class Big_Class:
> 
>     self.dictionary={'val_0':0, 'val_1':0, 'val_2':0, 'val_3':0}
> 
>     def func_0(self,destination,source):
>         self.dictionary[destination]=self.dictionary[source]
> 
>     def func_1(self,destionation,integer):
>         self.dictionary[destination]=integer
> 
>     def func_2(self,destination,source_0,source_1)
>         self.dictionary[destination]=self.dictionary[source_0]+self.dictionary[source_1]
> 
> What I would like to do is break each of those functions (but pretend each function is really about
> 30 functions) up into a seperate class, all which read and write to the same dictionary.  My real
> code has about 200 functions, that can be split into 5 or 6 general categories and my dictionary has
> about 50 enteries, all of which are used in each smaller process.
> 

Hmm,

Different categories may suggest different classes, one dict suggests
one class.
Difficult to give additional suggestions without knowing more.

Hope this helps,

Roeland

-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"