Python的getattr函数方法学习使用示例

作者:waws520 时间:2021-10-18 13:43:25 

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

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

举个栗子:

class A(object):
   def __init__(self, a, b):
       self.a1 = a
       self.b1 = b
       print('init')
   def mydefault(self, *args):
       print('default:' + str(args[0]))
   def __getattr__(self, name):
       print("other fn:", name)
       return self.mydefault
a1 = A(10, 20)
a1.fn1(33)
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

来源:https://juejin.cn/post/7119458309400166437

标签:Python,getattr,函数
0
投稿

猜你喜欢

  • Oracle针对数据库某一行进行操作的时候,如何将这一行加行锁

    2009-03-06 10:37:00
  • 3个常用的JS时间代码

    2009-03-22 15:29:00
  • ASP实现下载系统防盗链方法

    2008-02-01 14:05:00
  • Python编程快速上手——strip()函数的正则表达式实现方法分析

    2022-07-24 07:08:59
  • Python全栈之文件函数和函数参数

    2023-05-11 02:28:21
  • 如何在 IE 中使用 HTML5 元素

    2009-06-14 19:44:00
  • DBA_2PC_PENDING 介绍

    2009-02-28 10:59:00
  • Python中关键字is与==的区别简述

    2022-07-09 10:32:09
  • 运行SQL Server的计算机间移动数据库

    2009-01-20 13:07:00
  • MySQL表设计优化与索引 (九)

    2010-10-25 20:16:00
  • PHP中最低级别的错误类型总结

    2023-09-04 16:46:17
  • 小程序input数据双向绑定实现方法

    2023-07-15 13:09:54
  • python 对象真假值的实例(哪些视为False)

    2021-11-18 02:50:49
  • 一个asp伪静态的程序实现方法

    2010-06-28 18:56:00
  • 对python中的控制条件、循环和跳出详解

    2022-03-08 00:41:44
  • 如何使用Python标准库进行性能测试

    2023-04-27 07:48:52
  • 模式化窗口

    2009-06-18 18:41:00
  • php 模拟get_headers函数的代码示例

    2023-09-09 06:16:36
  • python Matplotlib基础--如何添加文本和标注

    2022-09-17 15:51:05
  • 网页优化之加速图片显示(CSS Sprite)

    2007-09-29 21:39:00
  • asp之家 网络编程 m.aspxhome.com