我知道这段代码是正确的:
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')()
这是错误的:
# will __getattr__ affect the getattr?
class a(object):
def __getattr__(self,name):
return 'xxx'
print getattr(a)
这也是错误的:
a={'aa':'aaaa'}
print getattr(a,'aa')
我们应该在哪里使用
__getattr__
和getattr
? 最佳答案
Alex的回答很好,但是自从您提出要求以来,它就为您提供了示例代码:)
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"
简而言之,答案是
你用
__getattr__
到定义如何处理未找到的属性和
getattr
到获得的属性关于python - __getattr__和getattr之间是什么关系?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1944625/