python note 24 (review)

Posted by nylex on Thu, 05 Mar 2020 18:45:36 +0100

1. Content Review

Object-oriented

Class variable
 Method
 : Static method
 Class method
 : Binding method
 : Attribute property

Singleton Module

Singleton module: design mode

Singleton scenarios

_u new_u(self): Instance creation, working before init

logging module

  • Logged

  • Logging errors, operation logs

  • For programmers to see: 1 Statistical use; 2 used for troubleshooting (debug); 3 record errors, complete optimization code.

  • logging.basicconig:1 Easy to use,2 Implementable,Coding problems;Cannot output to both file and screen.

  • logging.debug,logging.warning

  • logger object:

    Complex:
    1. Create a logger object;
    (2) Create a file operator;
    (3) Create a screen operator;
    (4) Create a format;
    Bind file operators to logger objects
     Bind screen operators to logger objects
     Format File Operators
     Format Screen Operators
     Use the logger object to operate on.
    import logging
    logger=logging.getLogger()
    fh=logging.FileHandler('log.log')
    sh=logging.StreamHandler()
    logger.addHandler(fh)
    logger.addHandler(sh)
    formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
    sh.setFormatter(formatter)
    fh.setFormatter(formatter)
    logger.warning('message')

collections module

from collections import OrderedDict
odic=OrderedDict([('a',1),('b',2),('c',3)])
print(odic)
# # odic['k']='k1'
# # odic['k1']='k2'
for k,v in odic.items():
    print(k,v)
#Module namedtuple
#There is no way to create a class where the values of all properties cannot be modified
from collections import namedtuple
Course=namedtuple('course',['name','price','teacher'])
python=Course('python',1980,'lexm')
print(python)
print(python.name)
=======================
course(name='python', price=1980, teacher='lexm')
python

====
//Read-only property: t property cannot be modified
import time
t=time.localtime()
print(t)

Project Development Specification

supplement

  • Stack, FIFO, lifo
  • Queue, fifo is queue, fifo

reflex

hasattr
setattr
getattr
class A:
    @staticmethod
    def func():
        print('12345')
    
getattr(A,)
delattr

Get instance variables, binding methods from objects

Get class variables, class methods, static methods from classes

Get any variable in the module (common variable, function, class) by the module name

Get any variables in this file from a text file.

getttr(sys.modules[__name__],'Variable Name')

Abstract Class/Interface Class

Is to give a specification to a subclass so that it must implement the method in accordance with the specification of an abstract class.

class Foo:
    def func(self):
        raise NotImplementedError

 class Son(Foo):
    pass

s=Son()
s.func()

Modules and packages

Module: The py file is written and provides some functionality directly to the programmer.

import,from import

What is a package:

Folder, a folder that stores multiple py files.

If a package is imported, the modules in this package will not be available by default.

The contents of the u init_u.py file need to be completed.

Importing a package is equivalent to executing the contents of an init.py file.

Project Specification

bin  start
#import os,sys
#base_path=os.path.dirname(os.path.dirname(__file__))#Current File
#sys.path.append(base_path)
#from src import core
conf  setting
src  Business logic
student.py
from src import core
core.py
from conf import settings
db  data file
lib  enlarge file
log  log file

Module Summary

os: operating system(Job: Calculate folder size, considering absolute path)
os.path.getsize('d:\code\s21')
#file
#file
#Route
#listdir,walk

sys
#The sys.path module searches for paths, and whether a module can be imported depends on whether there is a path for the module in sys.path.
#sys.argv, get command line parameters, python c://aaa.py remove file path
#sys.module, which stores all modules used in the current program and reflects the contents of the file.
json,Supports all languages
#Serialization, converting other types to str/bytes
#json format:
#1 All strings are double quotes
#2 The outermost layer can only be a list or a dictionary
#3 supports int float str list dict bool only
#4 A key with a dictionary can only be str
#5 cannot load multiple times in a row
pickle,Only supported py
#1 All data types can be written to a file
#2 Support continuous load multiple times
random(Operations, red bags, no one gets the same probability of amount, a total of 200 yuan, decimal inaccuracy ( print(random.uniform(1,5)))
import random
random.choice([1,2,3,4])#Randomly pick one
random.sample([1,2,3,4,5],3)#Extract Multiple
#randint
#choice
#sample                                                
#Shuffle, shuffle, algorithm

time
#Timestamp
#sleep() causes the program to pause ns
hashlib(Jobs, check file consistency, files, videos, pictures)
#md5
#sha
#import hashlib
#hashlib.md5('xxl'.encode()) -- Change MD5 to sha here if the sha algorithm is used
#md5.update('str'.encode())
#print(md5.hexdigest())

datetime
from datetime import datetime
dt=datetime.now()
print(datetime.timestamp(dt))
#now()
#utc()
#strftime('%Y-%m-%d') gets a datetime object
#timedelta(days=140), the addition of time
#Fromtimestamp timestamp to datetime
#timestamp(datetime object), datetime to timestamp
pickle
shutil
#import
shutil.make_archive()Compressed file, shutil.unpack_archive()Unzip the file, shutil.retree()Delete directory, shutil.move(),move file

#importlib
#import importlib
#importlib.import_module('module name')
#print(os.path.isdir('xxx')) to determine if it is a directory, isfile, or file                                                
copy
getpass,Show in command line ciphertext
                                                
copy
                                                
logging
#Two configurations: basicconfig,logger
 collections
 #OderdDict,namedtuple,deque,defaultDict
  functools
 #reduce(add,iterable)                                               
                                                
                                                
                                                

Object-oriented

Three main features: encapsulation, inheritance, polymorphism
 #Encapsulation:
(1) Generalized encapsulation: members of a class
 (2) Narrow encapsulation: private members, u names, are only used inside a class and cannot be called outside.
#Inheritance, all lookup names (invocation methods and properties) are first to find themselves, not their own parent
 #If you and your parent have both, you want both to be called, and super() specifies the class name to be called directly
 1. Parent, Base, Superclass
 (2) Derived classes, subclasses
 (3) Multiple inheritance, search order, depth first, breadth first
 (4) Single inheritance, subclasses can use the method of the parent class
 #Polymorphism
 -Multiple states represented by one class and similar states represented by multiple classes
 -user class, user class
-vip_user
-svip_user
 1 Duck type
#vip_user,svip_user
#list,tuple
 Basic concepts:
#What is a class: A class of things with the same methods and attributes
 #What is an object, an instance: a specific individual with specific attribute values and actions
 #Instantiation: The process of getting a specific object from a class
 #Instance
 #Instantiation
 Combination:
#Objects of one class as instance variables of objects of another class
 Class members: class variables, binding methods,
Special member: class method classmethod
 Static method:staticmethod
 property:

Special Members
 Double Bottom Method, Magic Method, Built-in Method
#__str__
_u new_u, construction method
 _u init_u, Initialization Method
__dict__
_u call_u, object can be used with parentheses
 _u enter_u, u exit_u, with context management
__getitem__
__setitem__
__delitem__
_u add_u, two objects added
__iter__
__dict__

Related built-in functions: isinstance, object and class
 issubclass, class, and class
 Type, type, class=type (object)
super follows mro order to find the previous class's

New and Classic Classes:
py2 inherits object s as new-style classes
 #Classic class by default
 py3 are all new-style classes, inheriting object s by default

New Class:
#Inherit object
 Supports super
 Multiple Inheritance, Width First
 mro method

Classic Classes:
#py2 does not inherit object s
 #No super syntax
 #Multiple Inheritance Depth First
 No mro method

Topics: Python Attribute JSON