class scope workarounds

Warren Postma embed at geocities.com
Tue Mar 28 20:14:51 CEST 2000


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:

class inherited(baseclass):
    x = 9

Anyways, since the above doesn't do what I wanted, here is an example with a
minimal workaround:



class baseclass:
    x = 7 # set initial values for class (once, at program start)
    def __init__(self):  # set initial values for instance (every time
object created)
        self.a = self.getx()*100 # this better get the right `x`
        self.b = self.getx()*1000
        self.c = self.getx()*10000
    def getx(self): # must override getx() when you inherit from baseclass
        return baseclass.x

    def a_method(self,b): # avoid referencing x directly, instead use getx()
        return b*self.getx(); # this better get the right `x`, too

# if you inherit, and if you change x, then you have to change getx():
class inherited(baseclass):
    x = 99
    def getx(self):    # override
        return inherited.x

# try it
ob1 = baseclass()
ob2 = inherited()
print ob1.a_method(10), ob1.a, ob1.b, ob1.c
print ob2.a_method(10), ob2.a, ob2.b, ob2.c

# correct output:

# 70 700 7000 70000
# 990 9900 99000 990000



Anyways, two things bug me about this:

1. It seems to me that Python 'should' be going to the class record of the
actual class you use when you invoke a_method() to resolve `x', not always
the base class. Why is it that it doesn't?

2. Since I have to make a method call, I incur function-invocation overhead,
which I'd sooner avoid.

Any suggestions on better ways to handle this?

---

Warren Postma





More information about the Python-list mailing list