Accessing class-level variables

Gerhard Häring gerhard at bigfoot.de
Wed Apr 24 05:48:12 EDT 2002


In article <Xns91FA105A11462RASXnewsDFE1 at 130.133.1.4>, Philip Swartzleonard wrote:
> 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

Heh. Thanks for the example code. But my needs are weirder. I really do want to
access the class variables of a *derived* class from the *superclass* 8-) These
are available for an instance method (it doesn't matter where the instance
method is defined, be it in the superclass or in the derived class), by using
self.__class__. One more reason why Python's explicit 'self' is useful.

I also can't explain the behaviour your code shows using the Language
Specification. http://www.python.org/doc/current/ref/class.html doesn't say how
inheritance affects class variables. Anybody can explain me how this works?

Gerhard



More information about the Python-list mailing list