1 class People:
2 __instance= False
3 def __init__(self,name,age):
4 self.name=name
5 self.age=age
6
7 def __new__(cls, *args, **kwargs):
8 if cls.__instance: #如果instance有值为true 那么直接返回之前创建的对象
9 return cls.__instance
10 cls.__instance=object.__new__(People) #如果__instance等于false 就创建一个对象 并返回对象给instance
11 return cls.__instance
12
13 p1=People('Kevin',23)
14 p1.hollday='reading'
15 print(p1.name,p1.age,p1.hollday)
16 p2=People('lisa',22)
17 print(p2.name,p2.age,p2.hollday) #这里使用的hollday 还是原来p1的属性
18 #单例模式相当于同一个类只能实例化一个对象,可以改变对象的属性
1 class People:
2 def __init__(self,name,age,sex):
3 self.name=name
4 self.age=age
5 self.sex=sex
6
7 def __eq__(self, other):
8 if self.name==other.name and self.sex==other.sex:
9 return True
10 else:
11 return False
12 def __hash__(self):
13 return hash(self.name+self.sex)
14 p1=People('kevin',23,'男')
15 p2=People('kevin',21,'男')
16 # print(p1==p2)
17 print(set((p1,p2)))
18 #set依赖 eq 和 hash
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>对象去重 eq 和hash
1 #哈希算法加密
2 import hashlib
3 sha=hashlib.sha256()
4 sha.update(b'115902553')
5 print(sha.hexdigest())
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1 import hashlib
2 with open('abc.txt','r+',encoding='utf-8')as f:
3
4 for lines in f:
5 lines=lines.strip()
6 md5 = hashlib.md5(lines.encode('utf-8'))
7 print(lines)
8 print(md5.hexdigest())
逐行读取文件内容并MD5加密