码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象 约束、自定义异常、加密

时间:2018-08-31 23:27:17      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:idt   basic   critical   多个   bst   none   src   ima   hfs   

1.约束

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


obj = Email()
obj.send(1)

 

开头定义一个约束函数,声明后边函数所使用的方法,主动抛异常raise NotImplementedError("方法(),   ")

抽象类和抽象方法的约束

接口中不允许写代码,只能约束,继承他的类,必须实现接口中定义的所有方法

Java中:interface  Foo:

      def f1(self,x1):pass#表示类中必须继承f1方法。可以实现多个接口。

 

###抽象类,约束继承他的派生类必须实现它其中的抽象方法

abstact class Foo:

  def f1(self):

    print(1,3,4)

  abstact def f2(self):pass#抽象方法

 

class Bar(Foo):

  def f2(self):

    print(123)

###Bar继承了Foo,就必须继承他的抽象方法,但是抽象类中的正常方法f1可以不用继承

 

 

python中的抽象类和抽象方法:

from abc import ABCMeta,abstractmethod
class Base(metaclass=ABCMeta):#抽象类
    
    def f1(self):
        print(123)
    @absabstractmethod#抽象方法
    def f2(self):
        pass

class Foo(Base):
     def f2(self):
        print(666)
obj = Foo()
obj.f1()
obj.f2()

 

总结:

1.什么是接口以及作用?

是一种数据类型,主要用与约束派生类中必须实现的指定方法,python中没有,Java和c#存在

2.python中使用什么来约束?

抽象类+抽象方法  编写上比较麻烦。

人为的主动抛出异常

3.约束时,抛出的异常可以使用其他方法

专业的写法:raise NotImplementedError(".send() 必须被重写.")

4.应用场景:多个类,内部必须有某些方法是是,需要使用基类加异常进行约束。

 

 

自定义异常:

以前的方法:

try:

a=a1

except Exception as e:

  print(e)

函数方法:

在文件中找关键字prev
import os
def func(path,prev) response={"colde":1000,"data:None} try: if not os.path.exists(path): response["code"]=1001 response["data"]="文件不存在" return response if onto prev: response["code"]=1002 response["data"]="关键字为空" return response except Exception as e : response["code"]=1003 response["data"]="未知错误" return response

 

面向对象
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

 

技术分享图片

加密:

引入hashlib模块(帮助加密)

obj=hashilb.md5(b"fhfshsjhjksd")#加盐

obj.update("admin".enode("utf-8))

v=obj.hexdigest()

print(v)

为防止撞库,使用加盐

 

 

日志:

引入模块logging

import logging
logger =logging.basicConfig(filename=日志.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("2")#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()

 

面向对象 约束、自定义异常、加密

标签:idt   basic   critical   多个   bst   none   src   ima   hfs   

原文地址:https://www.cnblogs.com/wqzn/p/9568580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!