内置函数之析构方法__del__

  1 # 01析构方法   __del__
  2 # 构造方法  申请一个空间
  3 # 析构方法  释放一个空间
  4 # 垃圾回收机制
  5 class A:
  6     def __del__(self):  # 析构方法
  7         print('析构方法')
  8 
  9 
 10 a = A()
 11 del a  # 对象的删除
 12 
 13 
 14 
 15 class File():
 16     def __init__(self, file_path):
 17         self.f = open(file_path)
 18         self.name = 'alex'
 19 
 20     def read(self):
 21         self.f.read(1024)
 22 
 23     def __del__(self):
 24         self.f.close()
 25 
 26 
 27 f = File('文件名')
 28 f.read()
 29 """
 30 
 31 
 32 # 02 item系列   和对象使用中括号访问值有联系
 33 # d = {'k': 'v'}
 34 # print(d)
 35 # print(d['k'])
 36 
 37 # 在内置的模块中,
 38 # 有一些特殊的方法,要求对象必须实现__getitem__/__setitem__才能使用
 39 class B:
 40     def __init__(self, lst):
 41         self.lst = lst
 42 
 43     def __getitem__(self, item):
 44         return getattr(self, item)
 45 
 46     def __setitem__(self, key, value):
 47         setattr(self, key, value)
 48 
 49     def __delitem__(self, key):
 50         delattr(self, key)
 51 
 52 
 53 b = B(['111', '222', '333', '444'])
 54 b['k1'] = 'v1'  # def __setitem__(self, key, value):
 55 
 56 print(b['k1'])  # def __getitem__(self, item):
 57 
 58 
 59 # del b['k1']            # def __delitem__(self, key):
 60 #
 61 # print(b['k1'])
 62 
 63 class B:
 64     def __init__(self, lst):
 65         self.lst = lst
 66 
 67     def __getitem__(self, item):
 68         return self.lst[item]
 69 
 70     def __setitem__(self, key, value):
 71         self.lst[key] = value
 72 
 73     def __delitem__(self, key):
 74         self.lst.pop(key)
 75 
 76 
 77 b = B(['111', '222', '333', '444'])
 78 print(b.lst[0])
 79 print(b[0])
 80 b[3] = 'alex'
 81 print(b.lst)
 82 del b[2]
 83 print(b.lst)
 84 # lis = ['黑桃', '红心', '梅花', '方片']
 85 # v = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
 86 # for i in lis:
 87 #     for j in range(len(v)):
 88 #         dic[j] = v[i]
 89 #         print(dic)
 90 
 91 # print(dic)
 92 dic = {}
 93 k1 = ['a', 'b', 'c']
 94 k2 = [4, 5, 6]
 95 
 96 for i in range(len(k1)):
 97     dic[k1[i]] = k2[i]
 98 print(dic)
 99 lst = []
100 lis = ['黑桃', '红心', '梅花', '方片']
101 v = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
102 for i in lis:
103     for n in v:
104         lst.append((i, n))
105 print(lst)

 

上一篇:Windows Server 2008 系统加固 windows日志查看与清理


下一篇:【python基础教程】魔法方法__init__,__str__,__del__的使用方法