Accessing class-level variables

Philip Swartzleonard starx at pacbell.net
Wed Apr 24 06:16:06 EDT 2002


Gerhard =?iso-8859-15?Q?H=E4ring?= || Wed 24 Apr 2002 02:48:12a:

> 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. 

Ah, i guess I missed something. Anyway, for what you want to do, I don't 
think there is another way. I'm just riding off of the global variables 
declared in my module, the class names. You have no idea what the 
relevant class name is or where it will be, so some form of 
introspection is the only way to get whay you need.

> 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? 

Hm. Well, it looks like the derived class just recives an extra binding 
of the inherited class. Here's a few tests on the subject:

>>> class C:
	a = [[1]]
>>> class D(C):
	pass
>>> C.a
[[1]]
>>> C.a[0] is D.a[0]
1
>>> C.a[0].append(2)
>>> D.a
[[1, 2]]
>>> C.a.append(3)
>>> C.a
[[1, 2], 3]
>>> D.a
[[1, 2], 3]

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



More information about the Python-list mailing list