Help with my program

Alan Gauld alan.gauld at btinternet.com
Fri Oct 23 04:34:32 EDT 2009


"tanner barnes" <tanner989 at hotmail.com> wrote

> I have a program with 2 classes and in one 4 variables 
> are created (their name, height, weight, and grade). 
> What im trying to make happen is to get the variables 
> from the first class and use them in the second class.

In general thats not a good idea. Each class should 
manage its own data and you should pass objects 
between objects. So first check that whatever your 
second class wants to do with the data from your first 
class can't be done by the first class itself via a method.

If you really do need to access the data there are 
several approaches:

1) Direct access via the object

class C:
   def __init__(s):
       s.x = 42

class D:
    def f(s, c):
       s.y = c.x    # direct access to a C instance

2) Access via a getter method returning each variable:

class C:
   def __init__(s):
       s.x = 42
   def getX(s):
       return s.x

class D:
    def f(s, c):
       s.y = c.getX()    # access via a getter method

3) Access via a logical operation that returns all public data

class C:
   def __init__(s):
       s.x = 42
       s.y = 66
   def getData(s):
       return (s.x, s.y)

class D:
    def f(s, c):
       s.x, s.y = c.getData()    # access via a logical access method

My personal preference in Python is (1) for occasional single 
value access (akin to a friend function in C++) or (3) for more 
regular access requests.

But most of all I try to avoid cross class data access wherever possible. 
As Peter Coad put it "Objects should do it to themselves...."
Otherwise known as the Law of Demeter.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Python-list mailing list