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

fab at slick.airforce-one.org fab at slick.airforce-one.org
Mon Oct 18 11:13:56 EDT 2010


Jean-Michel Pichavant <jeanmichel at sequans.com> wrote:
> Always post working code, or at least something we can paste in the 
> python interpreter (even if it's buggy)

Ok, noted.

> class A:
>    class B:
>        x=2
>    class C:
>        def __init__(self):
>            print A.B.x
> 
> c = A.C()
> 
> >2

Good, thanks.

I've made further tests and here is what I have come to:

class zoneDeDessin(gtk.DrawingArea):
  xmin = -5.5
  xmax = 5.5
  ymin = -5.5
  ymax = 5.5

  class Handle:
    def __init__(self, xEcran, yEcran):
      (self.xEcran, self.yEcran) = (xEcran, yEcran)
      (self.xRepere, self.yRepere) = (zoneDeDessin.XdeLEcranAuRepere(xEcran), zoneDeDessin.YdeLEcranAuRepere(yEcran))

  def __init__(self):      
    gtk.DrawingArea.__init__(self)
    (self.largeur, self.hauteur) = (0,0)

  def expose(self, widget, event):
    rect = self.get_allocation()
    (self.largeur, self.hauteur) = (rect.width, rect.height)
  
  def XdeLEcranAuRepere(self, x):
    return zoneDeDessin.xmin+x*(zoneDeDessin.xmax-zoneDeDessin.xmin)/float(self.largeur)   
  def YdeLEcranAuRepere(self, y):
    return zoneDeDessin.ymax+y*(zoneDeDessin.ymin-zoneDeDessin.ymax)/float(self.hauteur)

I have further code that should add a Handle when I double-click on
the screen.

However I get this error when executing:

Traceback (most recent call last):
  File "./zoneDeDessin.py", line 161, in boutonRelache
    zoneDeDessin.Courbe.ajouterUnHandle(self.courbeCourante, event.x, event.y)
  File "./zoneDeDessin.py", line 36, in ajouterUnHandle
    self.listeDesPoints.append(zoneDeDessin.Handle(xEcran, yEcran))
  File "./zoneDeDessin.py", line 22, in __init__
    (self.xRepere, self.yRepere) = (zoneDeDessin.XdeLEcranAuRepere(xEcran), zoneDeDessin.YdeLEcranAuRepere(yEcran))
TypeError: unbound method XdeLEcranAuRepere() must be called with zoneDeDessin instance as first argument (got float instance instead)

I understand the error (XdeLEcranAuRepere is an instance method, not a
class method), but I don't see how to fix it, except by making largeur
and hauteur class variables...

Any hint?

Thanks!

-- 
F. Delente



More information about the Python-list mailing list