python编程小提示

一.面向对象的约束

1.基于人为的约束

calss BaseMessage(object):
     def send(self,x):
      #必须继承BaseMessage,然后其中必须编写send方法.用于具体业务逻辑.
     raise NotImplementedError(".send() 必须被重写")
class Email(BaseMessage):
     def  send(self,x):
    #必须继承BaseMessage,然后其中必须编写send方法,用于完成具体逻辑
         return x
obj = Email()
obj,send(1)

如果Email类中未编写send(),仍继续使用继承父类的send(),则会报错打印  '.send() 必须重写'.父类中raise NotImplementedError有约束作用,提示子类必须编写send()方法.

2.抽象类和抽象方法的约束

from abc import ABCMeta,abstractmethod

class Base(metaclass=ABCMeta):  # 定义抽象类
    def f1(self):
        print('酸辣')

    @abstractmethod
    def f2(self):     #抽象方法
        pass
class Foo(Base):
    def f2(self):
        print('')

obj = Foo()
obj.f1()

Foo类只有编写父类抽象方法f2()时候,程序才可以正常进行,否则报错.

二.自定义异常处理

 有时在编写代码的时候我们需要编写异常情况,用到Exception万能处理时,有一个小小的缺点,就是不能提醒我们此时程序报的是什么错误,所以有时候我们要针对一些情况自定义异常处理.

import os
class ExistsError(Exception):
    pass
class KeyInvalidError(Exception):
    pass
def new_func(path,prev):
    response = {'code':1000,'data':None}
    try:
        if not os.path.exists():
            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
print(new_func("C:刘清扬PyCharm 2018.1.4python.py","we"))

这样我们就可以得到当'文件不存在','关键字为空'时出现的报错了.

class MyException(Exception):
    def __init__(self,code,msg):
        self.code = code
        self.msg = msg
try:
    raise MyException(100,'操作异常')

except KeyError as obj:
    print(obj,1111)
except MyException as obj:
    print(obj,222)                  #打印(100,'操作异常') 222
except Exception as obj:
    print(obj,3333)

三.为你的文件加密

在登录程序时,为了不让你的密码不被盗取,所以应该在储存密码时将明文改为密人,让隐私更安全.

import hashlib

def md5(pwd):
    obj = hashlib.md5()      
    obj.update(pwd.encode('utf-8'))
    return obj.hexdigest()
print(md5('21312e'))    #打印d09c5c2fd74e97e2e9e98bbc8d0a3e4b

将密码21312e转为密文  09c5c2fd74e97e2e9e98bbc8d0a3e4b

还可以继续为我们的密码加盐(严)

import hashlib
Salt = b'qwqw1212'    #加严
def md5(pwd):
    obj = hashlib.md5(Salt)
    obj.update(pwd.encode('utf-8'))
    return obj.hexdigest()
print(md5('21312e'))   打印81dda1ec99f8327b68659dbc56ee46c5

四.自定义日志

当我们写好程序给用户体验时,如果用户操作出报错信息,我们直接排查bug时将非常不方便.这时候我们编写一个日志功能,将报错详细录入,将会方便我们以后工作.

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)  #当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')

 五.python2和python3的区别

字符串:   python2:unicode   v = u"root"   本质上是用unicode存储(万国码)

     (str/bytes)          v = "root"      本质上用字节存储

    python3:str    v = "root"    本质上是用unicode存储(万国码)

        bytes   v = b"root"   本质上用字节存储

编码:   python2: 默认ascii  文件头可以修改,  #-*- encoding:utf-8

    python3: 默认utf-8  文件头也可以修改

继承:  python2:  经典类/新式类(object)

           python3:新式类

输入:  python2:    v = raw_input('')

          python3      v = input('')

打印:   python2 :  print 'xx'

       python3: print('xx')