vars between classes

Carel Fellinger cfelling at iae.nl
Tue May 30 17:18:38 EDT 2000


Marc Tardif <intmktg at Gloria.CAM.ORG> wrote:
> How can I maintain variables between classes and superclasses without
> passing explicitly as methods arguments? For instance:

I think you were confused by the diabolic behavior of "self.some_class_var".
Please refrain from using that construct whenever you deal with true class
variables. The "self." construct starts looking in the instance name space,
then looks in the class name space and then in all it's parent's classes
name spaces. So you can access a class var as if it were an instance var,
but only in expressions, *not* at the left-hand site of an assignment!
And only *prior* to an assignment to an instance var with that name!!!

The following annotated code will not only bewilder you, but alse give
you the behaviour you were after (if I guessed right:)

--------------------------------------------------------------------------
#! /usr/bin/python

import string

class A:
   mine = 'A'     # a class var

   def __init__(self):
      print "A's init, no instance var yet:", A.mine, self.mine,
      # now we create an instance variable shadowing the class var
      self.mine = string.lower(self.mine)
      print ", now with instance var:", A.mine, self.mine

   def mines(self):
      # return the class and instance variable mine
      return "printing A's: %2s %4s" % (A.mine, self.mine)

   def drink(self):
      # drinking gives us double vision, not our whole class
      self.mine = self.mine * 2


class B(A):

   def __init__(self):
      print "B initially without class var:", A.mine, self.mine,
      # now we create a clas variable shadowing the inherited one
      B.mine = 'B'
      print ', now with class var:', B.mine
      A.__init__(self)

   def mines(self):
      return A.mines(self) +\
             (", and B's: %4s %4s" % (B.mine, self.mine))

   def drink(self):
      # we drink like our parents,
      A.drink(self)
      # but we never drink alone, so the whole class gets drunk
      B.mine = B.mine * 2

   def booze(self):
      self.drink()
      # and if we really really drink our parents get drunk too
      A.mine = A.mine * 2


def print_abc(mess):
   print 'After', mess
   print 'a', a.mines()
   print 'b', b.mines()
   print 'c', c.mines()

a, b, c = A(), B(), B()
print_abc('instantiation')

b.drink()
print_abc('b.drink')

b.booze()
print_abc('b.booze')



-- 
groetjes, carel



More information about the Python-list mailing list