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?
Alex’s answer was good, but providing you with a sample code since you asked for it 🙂
So in short answer is
You use
__getattr__to define how to handle attributes that are not foundand
getattrto get the attributes