Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1188531
  • 博文数量: 287
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 2901
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
  • 认证徽章:
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(287)

文章存档

2019年(15)

2018年(43)

2017年(79)

2016年(80)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2019-03-16 13:55:14

python的getattr 用于normal attribute lookup fails的情况, 例如某 attribute不存在
而getattribute 会拦截所有的atttribute lookup 操作,不论这个attribute 存在与否

代码更清楚

点击(此处)折叠或打开

  1. class P:
  2.     x = 'a'
  3.     def __init__(self,n=0):
  4.         self.n = n

  5.     def __getattr__(self,name):
  6.         return("__geattr__ will be called when normal attribute get failed")

  7.     '''
  8.     def __getattribute__(self, name):
  9.         return("__getattribute__ will be called always")
  10.     '''

  11. def test_():
  12.     p = P()
  13.     print(p.x)
  14.     print(p.n)
  15.     print(p.__dict__)
  16.     #with parameter, equals p.__dict__
  17.     print(vars(p))
  18.     #searching for a attribute which is not exist
  19.     print(p.f)
  20.     print(getattr(p, 'n'))
  21.     print(getattr(p, 'x'))

  22. test_()


点击(此处)折叠或打开

  1. a
  2. 0
  3. {'n': 0}
  4. {'n': 0}
  5. __geattr__ will be called when normal attribute get failed
  6. 0
  7. a


点击(此处)折叠或打开

  1. class B:
  2.     x = 'ba'
  3.     def __init__(self,n=100):
  4.         self.n = n

  5.     def __getattr__(self,name):
  6.         return("__geattr__ will be called when normal attribute get failed")

  7.     def __getattribute__(self, name):
  8.         return("__getattribute__ will be called always")

  9. def test2_():
  10.     b = B()
  11.     print(b.x)
  12.     print(b.n)
  13.     print(b.__dict__)
  14.     #With parameter, equals to b.__dict__
  15.     print(vars(b))
  16.     #searching for a attribute which is not exist
  17.     print(b.f)
  18.     print(getattr(b, 'n'))
  19.     print(getattr(b, 'x'))

  20. test2_()
运行结果

点击(此处)折叠或打开

  1. __getattribute__ will be called always
  2. __getattribute__ will be called always
  3. __getattribute__ will be called always
  4. __getattribute__ will be called always
  5. __getattribute__ will be called always
  6. __getattribute__ will be called always
  7. __getattribute__ will be called always


阅读(82882) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
请登录后评论。

登录 注册