面向对象三,约束,加密

一,约束(类似于java的接口py中没有接口)

基于人为来约束

class BaseMessage(object):
    def send(self,x1):
        """
        必须继承BaseMessage,然后其中必须编写send方法。用于完成具体业务逻辑。
        """
        raise NotImplementedError(".send() 必须被重写.")

class Email(BaseMessage):
    def send(self,x1):
        """
        必须继承BaseMessage,然后其中必须编写send方法。用于完成具体业务逻辑。
        """
        print('发送邮件')


obj = Email()
obj.send(1)

抽象类和抽象方法约束 

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()
总结:
1. 什么是接口以及作用?
接口是一种数据类型,主要用于约束派生类中必须实现指定的方法。
Python中不存在,Java和C# 中是存在的。
2. Python中使用过什么来约束呢?
- 抽象类+抽象方法,编写上麻烦。
- 人为主动抛出异常

3. 约束时,抛出的异常是否可以用其他的?
不专业:raise Exception(".send() 必须被重写.")
专业:raise NotImplementedError(".send() 必须被重写.")

 

二.异常处理(类)

 

import os
class ExistsError(Exception):
    pass
class KeyInvalidError(Exception):
    pass
def new_func(path,prev):
    """
    去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。
        1000,成功
        1001,文件不存在
        1002,关键字为空
        1003,未知错误
        ...
    :return:
    """
    response = {'code':1000,'data':None}
    try:
        if not os.path.exists(path):
            raise ExistsError()

        if not prev:
            raise KeyInvalidError()
        pass
    except ExistsError as e:
        response['code'] = 1001
        response['data'] = '文件不存在'
    except KeyInvalidError as e:
        response['code'] = 1002
        response['data'] = '关键字为空'
    except Exception as e:
        response['code'] = 1003
        response['data'] = '未知错误'
    return response

def func(path,prev):
    """
    去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。
        1000,成功
        1001,文件不存在
        1002,关键字为空
        1003,未知错误
        ...
    :return:
    """
    response = {'code':1000,'data':None}
    try:
        if not os.path.exists(path):
            response['code'] = 1001
            response['data'] = '文件不存在'
            return response
        if not prev:
            response['code'] = 1002
            response['data'] = '关键字为空'
            return response
        pass
    except Exception as e:
        response['code'] = 1003
        response['data'] = '未知错误'
    return response

def show():
    return 8

def run():
    pass
异常处理
class MyException(Exception):
    def __init__(self,code,msg):
        self.code = code
        self.msg = msg
try:
    raise MyException(1000,'操作异常')

except KeyError as obj:
    print(obj,1111)
except MyException as obj:
    print(obj,2222)
except Exception as obj:
    print(obj,3333)
自定义异常

三.md5加密

在python3中使用hashlib模块进行md5操作

import hashlib

# 待加密信息
str = 'this is a md5 test.'

# 创建md5对象
hl = hashlib.md5()

# Tips
# 此处必须声明encode
# 若写法为hl.update(str)  报错为: Unicode-objects must be encoded before hashing
hl.update(str.encode(encoding='utf-8'))

print('MD5加密前为 :' + str)
print('MD5加密后为 :' + hl.hexdigest())

实例:

import hashlib
  #待加密信息
SALT = b'2erer3asdfwerxdf34sdfsdfs90'

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

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

 

四,日志

 

import logging

logger = logging.basicConfig(filename='xxxxxxx.txt',
                             format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                             datefmt='%Y-%m-%d %H:%M:%S',
                             level=30)

# logging.debug('x1') # 10
# logging.info('x2')  # 20
# logging.warning('x3') # 30
# logging.error('x4')    # 40
# logging.critical('x5') # 50
# logging.log(10,'x6')

import traceback

def func():
    try:
        a = a +1
    except Exception as e:
        # 获取当前错误的堆栈信息
        msg = traceback.format_exc()
        logging.error(msg)
func()

 

class Foo:

    def __str__(self):
        return 'asdfadfasdfasd'

obj = Foo()
print(obj,type(obj))  #asdfadfasdfasd <class '__main__.Foo'>

v1 = str(obj)
print(v1)  #asdfadfasdfasd
__str__眼见不一定为真
import logging

logger1 = logging.basicConfig(filename='x1.txt',
                             format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                             datefmt='%Y-%m-%d %H:%M:%S',
                             level=30)

logging.error('x4')
logging.error('x5')
日志文件个数
import logging


# 创建一个操作日志的对象logger(依赖FileHandler)
file_handler = logging.FileHandler('l1.log', 'a', encoding='utf-8')
file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s"))

logger1 = logging.Logger('s1', level=logging.ERROR)
logger1.addHandler(file_handler)

logger1.error('123123123')

# 在创建一个操作日志的对象logger(依赖FileHandler)
file_handler2 = logging.FileHandler('l2.log', 'a', encoding='utf-8')
file_handler2.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s"))

logger2 = logging.Logger('s2', level=logging.ERROR)
logger2.addHandler(file_handler2)

logger2.error('666')
自定义日志

 

posted @ 2018-08-31 20:57  清风_Z  阅读(162)  评论(0编辑  收藏  举报