Object oriented constraints, custom exceptions, encryption

1.constraint

class BaseMessage(object):
    def send(self,x1):
        """
        You must inherit BaseMessage, and then you must write the send method. Used to complete specific business logic."""
        raise NotImplementedError(".send() It must be rewritten.")
class Email(BaseMessage):
def send(self,x1):
"""
You must inherit BaseMessage, and then you must write the send method. Used to complete specific business logic.
"""
pass


obj = Email()
obj.send(1)

 

Define a constraint function at the beginning, declare the method used by the back function, and actively throw the exception raise NotImplementedError (“method (“).

The constraints of abstract classes and abstract methods

No code is allowed in the interface, only constraints, inherits his classes, and must implement all the methods defined in the interface

JavaChinese: interface Foo:

      def f1(self,x1):pass#Indicates that the F1 method must inherit from the class. Multiple interfaces can be implemented.

 

###The abstract class, which is bound to inherit his derived class, must implement the abstract method in it.

abstact class Foo:

  def f1(self):

    print(1,3,4)

  abstact def f2(self):pass#Abstract method

 

class Bar(Foo):

  def f2(self):

    print(123)

###BarIf you inherit Foo, you must inherit his abstract method, but the normal method F1 in the abstract class can be inherited without inheritance

 

 

pythonAbstract class and abstract method:

from abc import ABCMeta,abstractmethod
class Base(metaclass=ABCMeta):#abstract class
    
    def f1(self):
        print(123)
    @absabstractmethod#Abstract method
    def f2(self):
        pass

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

 

Summary:

1.What is interface and function?

It’s a data type that is used primarily with specified methods that must be implemented in constrained derived classes, not in python, and Java and c_# exist

2.pythonWhat is the use of constraint?

Abstract class + abstract method is rather troublesome to write.

Artificial initiative throwing exception

3.When thrown, exceptions can be thrown by other methods.

Professional Writing:raise NotImplementedError(.send() It must be rewritten.“)

4.Application scenario: Multiple classes, some of which must be internally constrained by base classes plus exceptions.

 

 

Custom exception:

Previous methods:

try:

a=a1

except Exception as e:

  print(e)

Function method:

Find keywords prev in files
import os
def func(path,prev) response={"colde":1000,"data:None} try: if not os.path.exists(path): response["code"]=1001 response["data"]="file does not exist" return response if onto prev: response["code"]=1002 response["data"]="Keyword is empty" return response except Exception as e : response["code"]=1003 response["data"]="unknown error" return response

 

Object-orientedimport os


class ExistsError(Exception):
    pass

class KeyInvalidError(Exception):
    pass

def new_func(path,prev):
    """
    Go to the path file, find a line of data prefixed with prev, get the data and return it to the caller.1000, success1001, the file does not exist.1002, the keyword is empty.1003, unknown error...: 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'] = 'file does not exist'
    except KeyInvalidError as e:
        response['code'] = 1002
        response['data'] = 'Keyword is empty'
    except Exception as e:
        response['code'] = 1003
        response['data'] = 'unknown error'
    return response

 

Encryption:

Introduce hashlib module (help encryption)

obj=hashilb.md5(b”fhfshsjhjksd”)#Salt adding

obj.update(“admin”.enode(“utf-8))

v=obj.hexdigest()

print(v)

To prevent storming, use salt.

 

 

Journal:

Introducing module logging

import logging
logger =logging.basicConfig(filename='Log.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 :#Get stack information
        msg=traceback.format_exc()
        logging.error(msg)
func()

 

Leave a Reply

Your email address will not be published. Required fields are marked *