Python类中方法getitem和getattr详解

yipeiwu_com6年前Python基础

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设计】。

相关文章

Python的“二维”字典 (two-dimension dictionary)定义与实现方法

本文实例讲述了Python的“二维”字典 (two-dimension dictionary)定义与实现方法。分享给大家供大家参考,具体如下: Python 中的dict可以实现迅速查找...

python 将print输出的内容保存到txt文件中

具体代码如下所示: import sys import os class Logger(object): def __init__(self, filename="Default...

python如何发布自已pip项目的方法步骤

前言 因为自已平时会把一个常用到逻辑写成一个工具python脚本,像关于时间字符串处理,像关于路径和文件夹遍历什么的工具。每一次新建一个项目的时候都要把这些工具程序复制到每个项目中,换一...

Python处理CSV与List的转换方法

1.读取CSV文件到List def readCSV2List(filePath): try: file=open(filePath,'r',encoding="gbk")#...

Python selenium的基本使用方法分析

本文实例讲述了Python selenium的基本使用方法。分享给大家供大家参考,具体如下: selenium是一个web自动化测试工具,selenium可以直接运行在浏览器上,可以接收...