Python的__getattr__方法学习

内容部分来自网络

__getattr__函数的作用: 如果属性查找(attribute lookup)在实例以及对应的类中(通过__dict__)失败, 那么会调用到类的__getattr__函数;

如果没有定义这个函数,那么抛出AttributeError异常。由此可见,__getattr__一定是作用于属性查找的最后一步

举个栗子:

复制代码
 1 class A(object):
 2     def __init__(self, a, b):
 3         self.a1 = a
 4         self.b1 = b
 5         print('init')
 6 
 7     def mydefault(self, *args):
 8         print('default:' + str(args[0]))
 9 
10     def __getattr__(self, name):
11         print("other fn:", name)
12         return self.mydefault
13 
14 
15 a1 = A(10, 20)
16 a1.fn1(33)
17 a1.fn2('hello')
复制代码

运行结果:

init
other fn: fn1
default:33
other fn: fn2
default:hello

第16行调用fn1属性时,查找不到次属性,程序调用__getattr__方法

用__getattr__方法可以处理调用属性异常

复制代码
class Student(object):
    def __getattr__(self, attrname):
        if attrname == "age":
            return 'age:40'
        else:
            raise AttributeError(attrname)

x = Student()
print(x.age)  # 40
print(x.name)
复制代码

这里定义一个Student类和实例x,并没有属性age,当执行x.age,就调用_getattr_方法动态创建一个属性,执行x.name时,__getattr__方法没有对其处理,抛出异常

age:40
  File "XXXX.py", line 10, in <module>
    print(x.name)
  File "XXXX.py", line 6, in __getattr__
    raise AttributeError(attrname)
AttributeError: name

下面展示一个_getattr_经典应用的例子,可以调用dict的键值对

复制代码
class ObjectDict(dict):
    def __init__(self, *args, **kwargs):
        super(ObjectDict, self).__init__(*args, **kwargs)

    def __getattr__(self, name):
        value = self[name]
        if isinstance(value, dict):
            value = ObjectDict(value)
        return value


if __name__ == '__main__':
    od = ObjectDict(asf = {'a': 1}, d = True)
    print(od.asf, od.asf.a)  # {'a': 1} 1
    print(od.d)  # True
复制代码

 

posted @   Monogem  阅读(10536)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示