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
投稿

猜你喜欢

  • MyBatis 如何写配置文件和简单使用

    2024-01-26 08:01:18
  • Django中的DateTimeField和DateField实现

    2021-02-03 20:38:13
  • javascript实现无缝上下滚动特效

    2024-05-11 09:35:08
  • Python实现RGB等图片的图像插值算法

    2023-03-30 17:11:55
  • Python中使用中文的方法

    2021-09-26 05:46:39
  • Python 虚拟环境venv详解

    2021-04-12 03:44:14
  • vue中记录滚动条位置的两种方法

    2024-04-27 15:59:33
  • Python学习之configparser模块的使用详解

    2022-07-21 23:21:25
  • mysql5.6.19下子查询为什么无法使用索引

    2024-01-15 01:04:29
  • 详解python调度框架APScheduler使用

    2021-11-05 22:55:36
  • Python脚本在Appium库上对移动应用实现自动化测试

    2021-12-27 12:43:24
  • python中copy()与deepcopy()的区别小结

    2022-02-22 19:39:14
  • Matlab常用的输出命令disp与fprintf解读

    2022-03-18 17:13:58
  • Python3.6中Twisted模块安装的问题与解决

    2022-05-29 15:45:02
  • flask框架路由常用定义方式总结

    2021-04-18 22:12:29
  • SQL Server 更改DB的Collation

    2024-01-26 23:22:35
  • Go语言单例模式详解

    2024-01-30 08:42:41
  • 关于SQL Server数据库中转储设备分析

    2009-01-21 14:55:00
  • js不能获取隐藏的div的宽度只能先显示后获取

    2024-04-17 10:25:17
  • Python遗传算法Geatpy工具箱使用介绍

    2021-11-02 02:21:16
  • asp之家 网络编程 m.aspxhome.com