somepeople

Python面向对象之__getitem__、__setitem__、__delitem__

#item方法
#__func__在类内实例化的时候根据条件自动触发
class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    #获取方法
    def __getitem__(self, item):
        print('get_item')
        return self.__dict__.get(item)
    #修改或新增方法
    def __setitem__(self, key, value):
        print('set_item')
        self.__dict__[key] = value
    #删除方法
    def __delitem__(self, key):
        print('del_item')
        self.__dict__.pop(key)


s1 = Student('ryan',18)
s2 = Student('tom',19)
s3 = Student('tracy',20)
s1['name']
s1['sex'] = 'man'
del s1['name']
print(s1['name'])

#get_item
#set_item
#del_item
#get_item
#None

 __getattr__、__setattr__、__delattr__

class teacher:
    def __getattr__(self, item):
        print(item,'不存在')
    def __setattr__(self, key, value):
        self.__dict__[key] = value
    def __delattr__(self, item):
        self.__dict__.pop(item)
    pass
t1 = teacher()
t1.name
t1.name = 'ryan'
print(t1.name)
del t1.name
t1.name

  #name 不存在
  #ryan
  #name 不存在

__getattr__只有在使用点调用属性且属性不存在的时候才会触发
__setattr__添加/修改属性会触发它的执行
__delattr__删除属性的时候会触发

 

posted on 2020-09-01 22:24  Hello_Thanos  阅读(288)  评论(0编辑  收藏  举报

导航