python魔法函数之__getattr__与__getattribute__
2024-10-07 10:33:34
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)
结果:
最新文章
- 关于smarty的一些个人笔记
- AFNetworking 2.0指北
- [HDU5903]Square Distance(DP)
- 无法在提交表单前通过ajax验证解决办法
- Qlikview 图标控件实现动态分组
- 边工作边刷题:70天一遍leetcode: day 85-1
- EF入门 IQueryable和IEnumberable的区别
- 安装ADT Cannot complete the install because one or more required items could not be found.
- Apache FileUpload详细介绍
- STL——前闭后开区间表示法和function call 操作符
- iOS-Core Text 入门
- Z.ExtensionMethods 扩展类库
- Cocos2d-x 3.2 Lua演示样例 ClickAndMoveTest(点击移动測试)
- js实现轮播图效果(附源码)--原生js的应用
- Python+selenium打开网页
- POST方式提交乱码解决
- FFmpeg源代码简单分析:avcodec_close()
- JAVA8 之 Stream sorted() 示例
- 由 UWP 版网易云音乐闪退引发的博文
- Pretty Smart? Why We Equate Beauty With Truth
热门文章
- NoClassDefFoundError与ClassNOtFoundException的区别
- C#Windows 服务的安装说明
- MFC工作者线程
- axios 在Vue全局引入的方法
- Hibernate_day04
- ubuntu14.04安装opencv-python
- openstack Q版部署-----Cinder云存储服务(10)
- 【转】MySQL-Select语句高级应用
- A Light CNN for Deep Face Representation with Noisy Labels
- Keepalived详解(五):Keepalived集群中MASTER和BACKUP角色选举策略【转】