Object oriented three, constraint, encryption

One, constraint (similar to java interface py has no interface)

Artificial constraints

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."""
        print('Send mail')


obj = Email()
obj.send(1)

Abstract class and abstract method constraint 

from abc import ABCMeta,abstractmethod


class Base(metaclass=ABCMeta): # abstract class

    def f1(self):
        print(123)


    @abstractmethod
    def f2(self):   # Abstract method
        pass

class Foo(Base):

    def f2(self):
        print(666)


obj = Foo()
obj.f1()
Summary:
1. What is interface and function?
A data type is used in interfaces to implement the specified method in constraint derived classes.
PythonIt does not exist in Java and C#.
2. PythonWhat has been used to constrain it?
- Abstract class + abstract method is difficult to write.
- Human initiative throws exceptions

3. Is it possible to throw exceptions when using constraints?
Unprofessional: raise Exception (".Send ()) must be rewritten."
Major: raise NotImplementedError (".Send ()) must be rewritten."

 

Two. Exception handling (class)

 

import 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

def 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):
            response['code'] = 1001
            response['data'] = 'file does not exist'
            return response
        if not prev:
            response['code'] = 1002
            response['data'] = 'Keyword is empty'
            return response
        pass
    except Exception as e:
        response['code'] = 1003
        response['data'] = 'unknown error'
    return response

def show():
    return 8

def run():
    pass

exception handling

class MyException(Exception):
    def __init__(self,code,msg):
        self.code = code
        self.msg = msg
try:
    raise MyException(1000,'Operation abnormality')

except KeyError as obj:
    print(obj,1111)
except MyException as obj:
    print(obj,2222)
except Exception as obj:
    print(obj,3333)

Custom exception

Three.Md5 encryption

Using python3 module to operate MD5 in hashlib

import hashlib

# Information to be encrypted
str = 'this is a md5 test.'

# Creating MD5 objects
hl = hashlib.md5()

# Tips
# Encode must be declared here.
# If written in hl.update (STR), the error is: Unicode-objects must be encoded before hashing
hl.update(str.encode(encoding='utf-8'))

print('MD5Before encryption,' + str)
print('MD5After encryption,' + hl.hexdigest())

Example:

import hashlib
  #Information to be encryptedSALT= b'2erer3asdfwerxdf34sdfsdfs90'

def md5(pwd):
    # Instantiated object
    obj = hashlib.md5(SALT)
    # Write the byte to be encrypted
    obj.update(pwd.encode('utf-8'))
    # Get the ciphertext
    return obj.hexdigest() # 21232f297a57a5a743894a0e4a801fc3 # 66fbdc0f98f68d69cd458b0cee975fe3 # c5395258d82599e5f1bec3be1e4dea4a

user = input("Please enter user name:")
pwd = input("Please input a password:")
if user == 'oldboy' and md5(pwd) == 'c5395258d82599e5f1bec3be1e4dea4a':
    print('Login success')
else:
    print('Login failure')

 

Four, log

 

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:
        # Gets the stack information of the current error
        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__Seeing is not always true.

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

Number of log files

import logging


# Create an operation log object logger (depending on 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')

# The object logger that creates an operation log (depends on 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')

Custom log

 

Leave a Reply

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