首页 > 代码库 > python基础----__setitem__,__getitem,__delitem__

python基础----__setitem__,__getitem,__delitem__

class Foo:    def __init__(self,name):        self.name=name    def __getitem__(self, item):        print(self.__dict__[item])    def __setitem__(self, key, value):        self.__dict__[key]=value    def __delitem__(self, key):        print(del obj[key]时,我执行)        self.__dict__.pop(key)    def __delattr__(self, item):        print(del obj.key时,我执行)        self.__dict__.pop(item)f1=Foo(sb)f1[age]=18f1[age1]=19del f1.age1del f1[age]f1[name]=alexprint(f1.__dict__)

 

#把对象操作属性模拟成字典的格式class Foo:    def __init__(self,name):        self.name=name    def __setattr__(self, key, value):        print(setattr===>)    def __getitem__(self, item):        # print(‘getitem‘,item)        return self.__dict__[item]    def __setitem__(self, key, value):        print(setitem-----<)        self.__dict__[key]=value    def __delitem__(self, key):        self.__dict__.pop(key)        # self.__dict__.pop(key)    # def __delattr__(self, item):    #     print(‘del obj.key时,我执行‘)    #     self.__dict__.pop(item)f=Foo(egon)f.name=egonlinf[name]=egonlinhai# print(f.name)# f.name=‘egonlin‘# f[‘age‘]=18# print(f.__dict__)## del f[‘age‘] #del f.age# print(f.__dict__)# print(f[‘name‘])

 

python基础----__setitem__,__getitem,__delitem__