[Tutor] Working with Python Objects

Alan Gauld alan.gauld at btinternet.com
Sun Mar 16 09:48:43 CET 2008


"Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote

> I've combined your code fragments and added a function 
> call too, to determine how 'a' is passed between objects 
> and classes:

-------------------------
class A:
    def oneA(self):
        z = 2
        self.a = self.a * z

class B:
    def oneB(self):
        inA = A()                 # instance of class A
        y = 5
        b = y * inA.a
        c = addNumbers(y, b)
-------------------

> Is this correct?

Not really.
First the line in oneA that assigns to self.a won't work 
because self.a doesn't exist at that point. So you can't 
multiply it by z. You might want to introduce an __init__ 
method to initialize self.a to some value:

Secondly by creating an instance of A inside oneB you 
create a new instance of A each time. That instance will 
always have the same value. You would be better creating 
an instance of A outside of B and passing that into B's 
methods. Like this:

class A:
    def __init__(self, aValue = 0) # initialize witrh a default value
       self.a = aValue                 # create self.a

    def oneA(self):
        z = 2
        self.a = self.a * z             # this now works

class B:
    def oneB(self, anA):      # pass in an instance of A
        y = 5
        b = y * anA.a
        print b

def addNumbers(anA,aB):
     theA = A(42)
     theB = B()
     theA.oneA()      # sets theA.a to 84
     theB.oneB(theA)   # pass theA to B.oneB

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list