Python constraints and MD5 encryption writing

There are two ways to write constraints in python

  1. Commonly used to actively throw exceptions through inheritance relationships
  2. Through abstract class + abstract method

1 Commonly used way of actively throwing exceptions through inheritance

No exception will be thrown when reporting errors in this send method.

class BaseMessage(object):
    def send(self):
    """
    必须继承BaseMessage,然后其中必须编写send方法。用于完成具体业务逻辑。
    """
    raise NotImplementedError(".send() 必须被重写.")   # 主动抛异常NotImplementedError,用exception也行但显得不专业
    # raise Exception(".send() 必须被重写.")

class Email(BaseMessage):               # 继承 BaseMessage  必须约束有send方法才行
    def send(self):
        pass                 # 发送邮件类
    def f1(self):
        pass
    def f2(self):
        pass

class Wechat(BaseMessage):           # 继承 BaseMessage  必须约束有send方法才行
    def send(self):
        pass               # 发送微信类
    def f1(self):
        pass

The BaseMessage class is used to constrain and constrain its derived classes: ensure that the send method must be written in the derived class, otherwise an error may be reported when executed.

2 Through abstract class + abstract method (not commonly used because of the trouble of writing)

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from abc import ABCMeta,abstractmethod

class Base(metaclass=ABCMeta): # 抽象类

    def f1(self):
        print(123)

    @abstractmethod                  # 抽象方法装饰器
    def f2(self): # 抽象方法
        pass

class Foo(Base):
    def f2(self):
        print(666)

obj = Foo()
obj.f1()

encryption

Encryption is irreversible, in order to prevent database collision, there must be a salting operation

import hashlib         # 导入hashlib 模块

SALT = b'2erer3asdfwerxdf34sdfsdfs90'               #  盐 盐必须是字节码

def md5(pwd):                # 传入密码
    # 实例化对象      加盐
    obj = hashlib.md5(SALT)                                      
    # 写入要加密的字节
    obj.update(pwd.encode('utf-8'))
    # 获取密文
    return obj.hexdigest() # 21232f297a57a5a743894a0e4a801fc3 # 66fbdc0f98f68d69cd458b0cee975fe3 

user = input("请输入用户名:")
pwd = input("请输入密码:")
if user == 'oldboy' and md5(pwd) == 'c5395258d82599e5f1bec3be1e4dea4a':
    print('登录成功')
else:
    print('登录失败')

Guess you like

Origin blog.csdn.net/qdPython/article/details/112672431