Classes in a class: how to access variables from one in another

John Nagle nagle at animats.com
Mon Oct 18 13:39:22 EDT 2010


On 10/18/2010 8:17 AM, Christian Heimes wrote:
> Am 18.10.2010 16:35, schrieb fab at slick.airforce-one.org:
>> So my way of coding it is the following:
>>
>> class zone(GtkDrawingArea):
>>
>>    class systemOfCoordinates:
>>      self.xmin = -5
>>      self.xmax = 5
>>      self.ymin = -5
>>      self.ymax = 5
>>
>>    class Curve:
>>      self.listOfPoints = ()
>>
>>      def draw(self):
>>        pass

    No, that's not the way to do it.  You're not clear on the
difference between a class and an object instance.  Data
is normally stored in object instances, not classes themselves.
(You can store data in a class itself, but that's just creates a single
global variable.  That's rarely done.)

    Something like this is more usual:

class SystemOfCoordinates(object) :

     def __init__(self, xmin, xmax, ymin, ymax) :
         self.xmin = xmin
         self.xmax = xmax
         self.ymin = ymin
         self.ymax = ymax

class Curve(object) :
     ...
	

class Zone(GtkDrawingArea) :

     def __init__(self, xmin, xmax, ymin, ymax)
         self.coords = SystemOfCoordinates(xmin, xmax, ymin, ymax)

     ....

myzone = Zone(0,200,0,200) # make a Zone
...
myzone.Curve(....)
...
myzone.draw()



When you call Zone like that, an empty Zone object is created and the 
__init__ function of Zone is called to fill it.  That function in turn 
calls SystemOfCoordinates, which calls the __init__ function of 
SystemOfCoordinates, which returns a SystemOfCoordinates object.
That's stored in "self.coords", a data attribute of the Zone object.
You get back a filled-in Zone object, which you can then use.

				John Nagle
	



More information about the Python-list mailing list