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

Nobody nobody at nowhere.com
Mon Oct 18 11:14:45 EDT 2010


On Mon, 18 Oct 2010 14:35:58 +0000, fab wrote:

> 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

"self" isn't meaningful within a class definition.

It's far from clear what the intent of your code is.

It's not even clear whether you understand the difference between a
class and an object.

> 
>   class Curve:
>     self.listOfPoints = ()

"self" isn't meaningful within a class definition.

>     def draw(self):
>       pass
>       # for each point in self.listOfPoints: draw this point
>       # then draw the Bézier curve passing through these points 

In light of this, I'add assume that the above:

>   class Curve:
>     self.listOfPoints = ()

should have been:

    class Curve:
      def __init__(self):
        self.listOfPoints = ()

This will give each *instance* of Curve a member named "listOfPoints".

>   def __init__(self): # for the zone object
>      self.coord = self.systemOfCoordinates()
>      self.listOfCurves = ( self.Curve() )

I suspect that you should use a list [...] rather than a tuple (...) here.
The main difference is that you can modify a list, but you can't modify a
tuple.

> Now to actually draw the dot on the screen, I need to access
> coord.xmin, coord.xmax, coord.ymin and coord.ymax to Point.draw(). I
> could do this by passing a reference to Point.draw(), but I'd like to
> do this implicitely.
> 
> I guess that in that case, xmin, xmax, ymin and ymax should be class
> variables of zone, right?

Not if you want to have more than one instance of zone. Class variables
are effectively global, i.e. you only have one set of variables regardless
of how many instances of the class you create. Putting them into a class
simply avoids "polluting" the module's top-level namespace.

If you don't want to pass the systemOfCoordinates to Point.draw, pass it
to Point.__init__. Or pass a reference to the zone to either of these.

If you're assuming that instances of a nested class get an implicit
reference to some instance of the outer class, you're mistaken.

Nested classes are simply a scoping feature, i.e. the name of the inner
class is added to the outer class' dictionary, not to the module's
dictionary. Other than that, the situation is no different than if the
inner class had been declared at the top level.

If you want objects to have a reference to some "parent" entity, you have
to explicitly pass the reference to the constructor and store it as an
instance member.




More information about the Python-list mailing list