properly implementing the __getattribute__()

Peter Otten __peter__ at web.de
Tue Oct 7 03:34:27 EDT 2003


Carlo v. Dango wrote:

> hello there. I have a hard time implementing __getattribute__ properly. I
> know I should stay away from that method, but Im doing some low-level
> changes to the dispatching and method-lookup, so I really don't have a
> choice ;-)
> 
> the following code
> 
> class Foo(object):
> def __init__(self):
> self.name = "hans"
> 
> def foo(self):
> print "foo"
> 
> class Bar(Foo):
> def info(self):
> print self.name
> 
> 
> b = Bar()
> print dir(b)
> print b.__dict__
> 
> results in
> 
> [...,  'foo', 'info', 'name']
> {'name': 'hans'}
> 
> 
> 
> But when I implement a simple __getattribute__
> 
> class Foo(object):
>     def __getattribute__(self, name): return object.__getattribute__(self,
> name)
> 
> def __init__(self):
> self.name = "hans"
> 
> def foo(self):
> print "foo"
> 
> class Bar(Foo):
> def info(self):
> print self.name
> 
> b = Bar()
> print dir(b)
> print b.__dict__
> 
> 
> I get
> 
> [...,  'info']
> {}
> 
> 
> so the method and the field decl of the super type is now gone :( And
> worse.. if i do a "b.foo()" it fails with the error AttributeError: 'Bar'
> object has no attribute 'foo'
> 
> I'm completely lost
> 
> Suggestions are deeply appreciated...
> 
> -Carlo v. Dango

It works as expected here on Linux with both Python 2.2.1 and 2.3

class Foo(object):
    def __getattribute__(self, name):
        return object.__getattribute__(self, name)

    def __init__(self):
        self.name = "hans"

    def foo(self):
        print "foo"

class Bar(Foo):
    def info(self):
        print self.name

def dir2(obj):
    default = dir(object())
    return [n for n in dir(obj) if not n in default]

b = Bar()
print dir2(b)
# ['__dict__', '__module__', '__weakref__', 'foo', 'info', 'name']

print b.__dict__
# {'name': 'hans'}

Maybe you are accidentally calling some old version of you test program?

Peter





More information about the Python-list mailing list