zjm1126 zjm1126 - 4 months ago 6
Python Question

What is the relationship between __getattr__ and getattr?

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:

print getattr(a,'aa')

Where should we use these functions (
) ?


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
>>> bar.b
"You asked for b, but I'm giving you default"
>>> getattr(bar, "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


getattr to get the attributes