目录
一、__format__
二、__del__
python从小白到总裁完整教程目录:https://blog.csdn.net/weixin_67859959/article/details/129328397?spm=1001.2014.3001.5502
一、__format__
- 自定制格式化字符串
date_dic = {
'ymd': '{0.year}:{0.month}:{0.day}',
'dmy': '{0.day}/{0.month}/{0.year}',
'mdy': '{0.month}-{0.day}-{0.year}',
}
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, format_spec):
# 默认打印ymd的{0.year}:{0.month}:{0.day}格式
if not format_spec or format_spec not in date_dic:
format_spec = 'ymd'
fmt = date_dic[format_spec]
return fmt.format(self)
d1 = Date(2016, 12, 29)
print(format(d1))
2016:12:29
print('{:mdy}'.format(d1))
12-29-2016
二、__del__
- __del__也称之为析构方法
- __del__会在对象被删除之前自动触发
class People:
def __init__(self, name, age):
self.name = name
self.age = age
self.f = open('test.txt', 'w', encoding='utf-8')
def __del__(self):
print('run======>')
# 做回收系统资源相关的事情
self.f.close()
obj = People('egon', 18)
del obj # del obj会间接删除f的内存占用,但是还需要自定制__del__删除文件的系统占用
print('主')
run=-====>
主