static attributes & __getattr__ override

Gordon McMillan gmcm at hypernet.com
Wed Apr 12 14:29:16 EDT 2000


Vadim Suvorov wrote:

> I am trying to redefine class attributes access, to include static
> attributes definitions from class (shared by all class instances). It is ok
> for instance to shade class attribute. So I wrote
> 
> class MyClass:
>     var1 = 1
>     var2 = 2
>     def __init__(self, x3):
>         self.var3 = x3
> 
>     def __getattr__(self, name):
>         return self.__class__.__dict__.get(name, None)
> 
> MyObj = MyClass(3)
> print MyObj.var1, MyObj.var2, MyObj.var3, MyObj.var4
> 
> (expected result) >>> 1 2 3 None
> 
> It works fine for attributes. 

Are you sure? Did you realize that only MyObj.var4 invokes 
__getattr__?

> However, I can not access standard methods of
> MyClass. I resorted to define __str__ and __repr__ (to be able to 'print
> MyObj'), and even then I could not use MyObj <> None which really hurts me.
> 
> Can you advice me on best way to proceed, and explain briefly what is going
> on? I do not think it is a bug, I probably missing something in the way
> attributes/methods work.

"obj.var" is the same as "getattr(obj, 'var')". Where obj is of 
InstanceType, that involves looking in the instance __dict__, 
the obj.__class__.__dict__, and then a search of the 
__dict__s of obj.__class__.__bases__. Only if all of that fails 
is the __getattr__ method tried.

Methods normally live in obj.__class__.__dict__, or in the 
__dict__ of one of the classes in __bases__. The only 
difference between a variable and a method is that the getattr 
code, upon finding it, will magically wrap it up into a bound 
method (squirrelling away the "self" pointer where the code 
object can make use of it).

- Gordon




More information about the Python-list mailing list