python之路——28

学习内容

1.字典通过__getitem__,__setitem__,__delitem__实现 对象[] 操作
2.__new__考试会考
3.单例模式 每个对象只有被允许有一个实例 __new__
4.__hash__ hash()
5.__eq__ ==
6.hashlib
提供摘要算法,
摘要功能:对相同的字符串使用同一个算法进行摘要,得到的值总是不变的
sha算法——随着复杂程度的增加,摘要的需要的时间、内存增加
摘要功能
1.密码的密文存储
2.文件的一致性验证
a.下载文件,检查本地与服务器上的文件是否一致
b.两台机器上的两个文件,检查文件是否相同
7.加盐
增强加密的安全性
md5 < 加盐 < 动态加盐
文件的一致性校验,不加盐

代码区

1.item内置函数

class Foo:
    def __init__(self,name):
        self.name = name
    def __getitem__(self, item):
        print(self.__dict__[item])
    def __setitem__(self, key, value):
        print('__setitem__')
        self.__dict__[key] = value
    def __delitem__(self, key):
        self.__dict__.pop(key)
        print('__delitem__')
    def __delattr__(self, item):
        self.__dict__.pop(item)
        print('__delattr__')

a1 = Foo('egon')
a1['name']
a1['age'] = 0
print(a1.__dict__)
del a1['age']
print(a1.__dict__)
del a1.name
print(a1.__dict__)

2.单例模式,每个对象只被允许有一个实例化

class Singleton:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,"_instance"):
            cls._instance = object.__new__(cls)
        return cls._instance
one = Singleton()
two = Singleton()
two.a = 3
print(one.a)
print(id(one))
print(id(two))
print(one == two)
print(one is two)

3.纸牌游戏

from collections import namedtuple
import json
import pickle
Card = namedtuple('Card',['rank','suit'])

class FranchDeck:
    ranks = [str(i) for i in range(2,11)] + list('JQKA')
    suits = ['红桃','黑桃','方块','梅花']
    def __init__(self):
        self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
                        for suit in FranchDeck.suits]
    def __getitem__(self, item):
        return self._cards[item]
    def __len__(self):
        return len(self._cards)
    def __setitem__(self, key, value):
        self._cards[key] = value
    def __str__(self):
        return json.dumps(self._cards,ensure_ascii=False)
# 抽牌比大小
deck = FranchDeck()
print(deck[10],type(deck[10]))
# from random import choice
# print(choice(deck))
# print(choice(deck))
# 洗牌
from random import shuffle
shuffle(deck)
print(deck)
print(deck._cards[:5])
print(deck[:5])

4.hashlib

import hashlib
pwd = 'sa12356'
md5 = hashlib.md5()
md5.update(bytes(pwd,encoding='utf-8'))
md5_pwd = md5.hexdigest()
print(md5_pwd)

猜你喜欢

转载自www.cnblogs.com/wan2-0/p/10805310.html
今日推荐