class Foo:
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):
print('正在执行delitem')
self.__dict__.pop(key)
f1 = Foo()
print(f1.__dict__)
f1['name'] = 'jinling'
print(f1.__dict__)
f1['age'] = 19
print(f1['age'])
print(f1.__dict__)
del f1['age']
print(f1.__dict__)
像上面这样实例化后以操作字典的方式增删查才可以实现
二、__str__ 及__repr__
可以自己定制str方法,控制打印的信息,由print 触发str
class Foo:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return '名字是{} 年龄是{}'.format(self.name,self.age)
f1 = Foo('jinling', 19)
print(f1) # -->str(f1)-->f1.__str__()
__repr__是在python解释中触发
当__str__ 与__repr__共存时
class Foo:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return "print会触发这个哦"
def __repr__(self):
return '名字是{} 年龄是{}'.format(self.name,self.age)
f1 = Foo('jinling', 19)
print(f1) # -->str(f1)-->f1.__str__()
如果__str__ 没有被定义, 那么就会使用__repr__来代替输出
注意:这俩方法的返回值必须是字符串,否则抛出异常
class Foo:
def __init__(self,name,age):
self.name = name
self.age = age
# def __str__(self):
# return "print会触发这个哦"
def __repr__(self):
return '名字是{} 年龄是{}'.format(self.name,self.age)
f1 = Foo('jinling', 19)
print(f1) # -->str(f1)-->f1.__str__()---->f1.__repr__()
三、定制__format__
format_dic = {
'ymd' : '{0.year}{0.mon}{0.day}',
'm-d-y':'{0.mon}-{0.day}-{0.year}',
'y:m:d':'{0.year}:{0.mon}:{0.day}'
}
class Date:
def __init__(self,year,mon,day):
self.year = year
self.mon = mon
self.day = day
def __format__(self, format_spec):
fh = format_dic[format_spec]
return fh.format(self)
d1 = Date(2019,10,6)
print(d1.__format__('y:m:d'))
改进一下:
format_dic = {
'ymd' : '{0.year}{0.mon}{0.day}',
'm-d-y':'{0.mon}-{0.day}-{0.year}',
'y:m:d':'{0.year}:{0.mon}:{0.day}'
}
class Date:
def __init__(self,year,mon,day):
self.year = year
self.mon = mon
self.day = day
def __format__(self, format_spec):
if not format_spec or format_spec not in format_dic: #format 的第二个参数为空或者不在创建好的字典里
format_spec = 'ymd'
fh = format_dic[format_spec]
return fh.format(self)
d1 = Date(2019,10,6)
print(d1.__format__('y:m:d'))
print(format(d1,"asdasd"))
print(format(d1))