class scope workarounds

Gordon McMillan gmcm at hypernet.com
Tue Mar 28 16:13:50 EST 2000


Warren Postma writes:

> Here's a sample bit of code I wrote to try to figure out the Python scoping
> rules with regards to class-level data members (what would be a static data
> member in a C++ class).
> 
> Let's suppose I have a base class with a class-scope variable 'x':
> 
> class baseclass:
>     x = 5 # inherited classes can override this
>     def a_method(a):
>         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:

Not clear what you mean by "correct", but I suspect you've 
overlooked the obvious <wink>:

>>> class A:
...  x = 1
...  def showx(self):
...   print self.x
...
>>> class B(A):
...  x = 2
...
>>> class C(B):
...  x = 3
...
>>> c = C()
>>> c.showx()
3
>>> b = B()
>>> b.showx()
2
>>>



- Gordon




More information about the Python-list mailing list