__getattr__和getattr之间是什么关系? [英] What is the relationship between __getattr__ and getattr?

查看:73
本文介绍了__getattr__和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')()   

这是错误的:

# 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?

Where should we use __getattr__ and getattr?

推荐答案

Alex的回答很好,但是自从您提出要求以来,它为您提供了示例代码:)

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"

总之,答案是

您使用

__getattr__定义如何处理未找到

getattr获取 属性

这篇关于__getattr__和getattr之间是什么关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆