What is the relationship between __getattr__ and getattr?

zjm1126 picture zjm1126 · Dec 22, 2009 · Viewed 13.9k times · Source

I know this code is right:

class A:   
    def __init__(self):
        self.a = 'a'  
    def method(self):   
        print "method print"  

a = A()   
print getattr(a, 'a', 'default')   
print getattr(a, 'b', 'default')  
print getattr(a, 'method', 'default') 
getattr(a, 'method', 'default')()   

And this is wrong:

# will __getattr__ affect the getattr?

class a(object):
    def __getattr__(self,name):
        return 'xxx'

print getattr(a)

This is also wrong:

a={'aa':'aaaa'}
print getattr(a,'aa')

Where should we use __getattr__ and getattr?

Answer

Kimvais picture Kimvais · Dec 22, 2009

Alex's answer was good, but providing you with a sample code since you asked for it :)

class foo:
    def __init__(self):
        self.a = "a"
    def __getattr__(self, attribute):
        return "You asked for %s, but I'm giving you default" % attribute


>>> bar = foo()
>>> bar.a
'a'
>>> bar.b
"You asked for b, but I'm giving you default"
>>> getattr(bar, "a")
'a'
>>> getattr(bar, "b")
"You asked for b, but I'm giving you default"

So in short answer is

You use

__getattr__ to define how to handle attributes that are not found

and

getattr to get the attributes