Accessing class-level variables

Philip Swartzleonard starx at pacbell.net
Wed Apr 24 04:35:10 EDT 2002


Gerhard =?iso-8859-15?Q?H=E4ring?= || Tue 23 Apr 2002 09:58:46p:

> * 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
>> =):
>> 
>> [...]
> 
> 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

Er, i think you're trying too hard. +) Now that i realized what you 
really want, I just tried this...:

>>> class A:
	d=5

>>> class B(A):
	pass

>>> B.d
5
>>> class B(A):
	def p(self):
		B.d += 1
		print B.d
		print A.d

>>> B().p()
6
5
>>> B().p()
7
5

-- 
Philip Sw "Starweaver" [rasx] :: www.rubydragon.com



More information about the Python-list mailing list