Python类中方法getitem和getattr详解
2019-08-30 14:46
3407 查看
1、getitem 方法
使用这个方法最大的印象就是调用对象的属性可以像字典取值一样使用中括号['key']
使用中括号对对象中的属性进行取值、赋值或者删除时,会自动触发对应的__getitem__、__setitem__、__delitem__方法
代码如下:
class Foo(object): def __init__(self): self.name = 'jack' def __getitem__(self,item): if item in self.__dict__: # item = key,判断该key是否存在对象的 __dict__ 里, return self.__dict__[item] # 返回该对象 __dict__ 里key对应的value def __setitem__(self, key, value): self.__dict__[key] = value # 在对象 __dict__ 为指定的key设置value def __delitem__(self, key): del self.__dict__[key] # 在对象 __dict__ 里删除指定的key f1 = Foo() print(f1['name']) # jack f1['age'] =10 print(f1['age']) # 10 del f1['name'] print(f1.__dict__) # {'age': 10}
2、getattr 方法
使用对象取值、赋值或者删除时,会默认的调用对应的__getattr__、__setattr__、__delattr__方法。
对象取值时,取值的顺序为:先从object里__getattribute__中找,第二步从对象的属性中找,第三步从当前类中找,第四步从父类中找,第五步从__getattr__中找,如果没有,直接抛出异常。
代码如下:
class Foo(object): def __init__(self): self.name = 'jack' def __getattr__(self, item): if item in self.__dict__: return self.__dict__[item] def __setattr__(self, key, value): self.__dict__[key] = value def __delattr__(self, item): del self.__dict__[item] c1 = Foo() print(c1.name) # jack c1.age = 18 print(c1.age) # 18 del c1.age # 删除 对象c1的age print(c1.age) # None
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
- 浅谈Python类的__getitem__和__setitem__特殊方法
- 解析Python中的__getitem__专有方法
- 详解Python中的__getitem__方法与slice对象的切片操作
- 详解Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码数
- 对比Python中__getattr__和 __getattribute__获取属性的用法
- 详解Python中 __get__和__getattr__和__getattribute__的区别
- python中的内置函数getattr()介绍及示例
- Python __getattr__与__setattr__使用方法
相关文章推荐
- 详解Python中的__getitem__方法与slice对象的切片操作
- 详解Python魔术方法__getitem__、__setitem__、__delitem__、__len__
- 详解Python魔术方法__getitem__、__setitem__、__delitem__、__len__
- Python3 魔法方法之(__getattr__()、__setattr__()、 __getitem__()、__setitem__())
- 详解Python中的__getitem__方法与slice对象的切片操作
- Python 一些特别函数 __getitem__ __getattr__
- 解析Python中的__getitem__专有方法
- 详解Python中 __get__和__getattr__和__getattribute__的区别
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- python 字典 setdefault()和get()方法比较详解
- python 魔法方法之:__getitem__ __setitem__ __delitem__
- Python 一些特别函数 __getitem__ __getattr__
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- python 魔法方法之:__getitem__ __setitem__ __delitem__ __len__
- Python类的__getitem__和__setitem__特殊方法
- Python的hasattr() getattr() setattr() 函数使用方法详解