[Tutor] Working with Python Objects

Greg Graham GGraham at cistercian.org
Fri Mar 14 21:57:58 CET 2008

Dinesh wrote:
> I've avoided it as long as possible but I've reached a stage where I
have to
> start using Python objects!  The primary reason is that the web
framework uses
> objects and the second is to eliminate a few globals.  Here is example
> code followed by the question (one of many I suspect!):
> class A:
>     constantA = 9
>     def OneOfA:
>             <do something>
>             a = <do something else>
> class B:
>     variableB = "quick brown fox"
>     def OneOfB:
>             <do something>
>             b = <do something more>
>             c = b * a        # the 'a' from def OneOfA in class A
> Question:
> 1) how do I access the 'a' from function (method) OneOfA in class A so
> it can be used by functions (methods) in class B?

I wrote the following classes as an example that might be what you want.

 1  class A(object):
 2       def one_of_a(self):  # self is required for a method
 3           self.a = 3
 4           print self.a
 6   class B(object):
 7       def one_of_b(self, a_obj):
 8           b = 10
 9           self.c = b * a_obj.a
10           print self.c

First of all, note that the method definitions have a "self" argument.
is how the method has access to the object for which they are called. If
you look on line 3, I put "self.a" so that the 3 is stored in the "a"
field of the object.

Since you wanted to access the a field of an A object in your one_of_b
it will need access to an A object, so I added a parameter that you can
to pass in an A object (line 7). Assuming an A object is passed in, then
a field of it can be accessed as in line 9, "a_obj.a".

Here is how I ran the code (using IPython):

In [17]: v1 = A()

In [18]: v1.one_of_a()

In [19]: v2 = B()

In [20]: v2.one_of_b(v1)

At [17], I create an instance of A and assign it to variable v1.
At [18] I call the one_of_a method on my newly created object, which
out a 3, the value stored in the "a" field of v1 object.
At [19], I create an instance of B and assign it to variable v2.
At [20], I call the one_of_b method on my new object, passing in the A
object assigned to v1. It prints out 30, which is 10 times the value
in the "a" field of v1.

The class, variable, and method names are pretty abstract and similar,
so I
hope that doesn't cause undue confusion. It might be easier to
with a more concrete example.


More information about the Tutor mailing list