Accessing class-level variables

Gerhard Häring gh_pythonlist at gmx.de
Wed Apr 24 00:58:46 EDT 2002


* Philip Swartzleonard <starx at pacbell.net> [2002-04-24 04:27 +0000]:
> Gerhard =?iso-8859-15?Q?H=E4ring?= || Tue 23 Apr 2002 09:04:04p:
> 
> > I'm trying to access a class variable in a derived class. I sincerly
> > hope there's a less kludgy way than what I'm currently using:
> > [...]
> > print self.__class__.a
> 
> Well, i knew this worked for dispatching __init__'s, but... well here 
> =):
> 
> Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE 0.8 -- press F1 for help
> >>> class A:
> 	d = 5
> 
> >>> class B:
> 	def p(self):
> 		print A.d
> 
> >>> z = B()
> >>> z.p()

Erh. Here you are accessing the class variable of class A explicitely. I
know how that's working :) But it's not what I want. I want to access
the class variable in a derived class. And even if I don't know what my
derived class is. Here's an example that is more to my real code:

import new

class X:
     def p(self):
         print self.__class__.a

def make_class(val):
    klass = new.classobj("Y", (X,), {"a": val})
    return klass

y = make_class(5)()
y.p()


This works, but using self.__class__.a is ugly.

Heh, now that I come to think of it, here I somehow have the class
inheritance backwards :-) Guess there's no other way, right?

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 9.5 °C      Wind: 3.3 m/s





More information about the Python-list mailing list