class scope workarounds

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Tue Mar 28 21:34:42 CEST 2000


Warren Postma wrote in comp.lang.python:
> class baseclass:
>     x = 5 # inherited classes can override this
>     def a_method(a):

Missing 'self' argument here, btw.

>         classvar x    # new keyword suggestion?
>         return a*x
> 
> Now suppose I want to inherit and change x, but lots of methods in baseclass
> reference x directly, and I want them to use the correct x for that
> base-class:
> 
> class inherited(baseclass):
>     x = 9

This is probably what you're looking for:

class baseclass:
   x = 5
   def a_method(self, a):
      return a*(self.__class__.x)
	  
class inherited(baseclass):
   x = 9
   
x = inherited()
x.a_method(1)

Returns 9.

I bet someone is going to point out problems with implementing
something like 'classvar'.

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
"This gubblick contains many nonsklarkish English flutzpahs, but the
 overall pluggandisp can be glorked from context"  (David Moser)



More information about the Python-list mailing list