getattr

在访问对象的属性不存在时,调用__getattr__,如果没有定义该魔法函数会报错

class Test:
def __init__(self, name, age):
self.name = name
self.age = age def __getattr__(self, item):
print(item) // noattr
return 'aa' test = Test('rain', 25)
print(test.age) // 25
print(test.noattr) //aa
getattribute

访问对象任何属性(即使属性不存在)都会调用__getattribute__

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : 04__getattr__与__getattribute__.py
@Time : 2018/12/18 21:06:50
@Author : Rain
@License : (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc : None
''' # here put code class Test:
def __init__(self, name, age):
self.name = name
self.age = age def __getattr__(self, item):
print(item)
return 'aa' def __getattribute__(self, item): # 尽量不要使用它
print('访问属性了')
return 'bbb' test = Test('rain', 25)
print(test.age)
print(test.noattr)

结果:

最新文章

  1. 关于smarty的一些个人笔记
  2. AFNetworking 2.0指北
  3. [HDU5903]Square Distance(DP)
  4. 无法在提交表单前通过ajax验证解决办法
  5. Qlikview 图标控件实现动态分组
  6. 边工作边刷题:70天一遍leetcode: day 85-1
  7. EF入门 IQueryable和IEnumberable的区别
  8. 安装ADT Cannot complete the install because one or more required items could not be found.
  9. Apache FileUpload详细介绍
  10. STL——前闭后开区间表示法和function call 操作符
  11. iOS-Core Text 入门
  12. Z.ExtensionMethods 扩展类库
  13. Cocos2d-x 3.2 Lua演示样例 ClickAndMoveTest(点击移动測试)
  14. js实现轮播图效果(附源码)--原生js的应用
  15. Python+selenium打开网页
  16. POST方式提交乱码解决
  17. FFmpeg源代码简单分析:avcodec_close()
  18. JAVA8 之 Stream sorted() 示例
  19. 由 UWP 版网易云音乐闪退引发的博文
  20. Pretty Smart? Why We Equate Beauty With Truth

热门文章

  1. NoClassDefFoundError与ClassNOtFoundException的区别
  2. C#Windows 服务的安装说明
  3. MFC工作者线程
  4. axios 在Vue全局引入的方法
  5. Hibernate_day04
  6. ubuntu14.04安装opencv-python
  7. openstack Q版部署-----Cinder云存储服务(10)
  8. 【转】MySQL-Select语句高级应用
  9. A Light CNN for Deep Face Representation with Noisy Labels
  10. Keepalived详解(五):Keepalived集群中MASTER和BACKUP角色选举策略【转】