Description Device
Get(self, instance, owner)
- Called when a property is accessed
Set(Self, instance, value)
- Called when an attribute is assigned a value
Delete(Self, instance)
Essence
- Adding a descriptor to a class can display the Add Class property or inject it with setattr
Note that the so-called class properties are not just similar to those of X=a (), and the functions defined in the class are also class properties
Analog Staticmethod and Classmethod
from functools import partialclass StaticMethod: def __init__(self, fn): self.fn = fn def __get__(self, instance, owner): return self.fnclass ClassMethod: def __init__(self, fn): self.fn = fn def __get__(self, instance, owner): return partial(self.fn, owner)class Test: @StaticMethod def s_mtd(): # s_mtd = StaticMethod(s_mtd) print(‘s_mtd‘) @ClassMethod def c_mtd(cls): # c_mtd = ClassMethod(c_mtd) print(‘c_mtd‘, cls)if __name__ == ‘__main__‘: Test.s_mtd() Test.c_mtd()
Mock property
class Property: def __init__(self, fget=None, fset=None): self.fget = fget self.fset = fset def __get__(self, instance, owner): return self.fget(instance) def __set__(self, instance, value): self.fset(instance, value) def getter(self): pass def setter(self, fset): self.fset = fset return selfclass Person: def __init__(self, name, age): self._name = name self._age = age @Property def name(self): # name=Property(name) return self._name @name.setter def name(self, value): # name=Property(name).setter(name) (value) self._name = value @Property def age(self): # name=Property(name) return self._age @age.setter def age(self, value): # name=Property(name).setter(name) (value) self._age = value
Check parameter Type General decorator
import inspectclass TypeCheck: def __init__(self, key, type): print(‘TC init‘) self.key = key self.type = type def __get__(self, instance, owner): print(‘TC get‘) if instance is not None: return instance.__dict__[self.key] return self def __set__(self, instance, value): print(‘TC set‘) if not isinstance(value, self.type): raise TypeError instance.__dict__[self.key] = valuedef typeassert(cls): params = inspect.signature(cls).parameters for name, type in params.items(): if type != type.empty: setattr(cls, name, type.annotation) return cls@typeassertclass Person: name = TypeCheck(‘name‘, str) age = TypeCheck(‘age‘, int) def __init__(self, name: str, age: int): self.name = name self.age = agetom = Person(‘tom‘, 12)print(tom.name)
Class Decorator
Import Inspectclass typecheck:def __init__ (self, Key, type): Print (' TC init ') Self.key = key Self . Type = Type Def __get__ (self, instance, owner): print (' TC get ') If instance are not None:retu RN Instance.__dict__[self.key] return self def __set__ (self, instance, value): Print (' TC set ') if Not isinstance (value, Self.type): Raise TypeError Instance.__dict__[self.key] = Valueclass Typeassert: def __init__ (self, cls): Self.cls = CLS-def __call__ (self, Name, age): params = Inspect.signature (self. CLS). Parameters for key, type in Params.items (): if Type! = Type.empty:setattr (Self.cls, Key, Typecheck (key, Type.annotation)) return Self.cls (name, age) @TypeAssertclass Person: # person = Typeassert (Pe Rson) name = Typecheck (' name ', str) age = Typecheck (' age ', int.) def __init__ (self, Name:str, age:int): s Elf.name = name SElf.age = Agetom = Person (' Tom ', ' ') ' Print (tom.name)
Linked list
Class Node: "" "Description:node Class attr item:current node ' s data attr next:points to the next node A TTR past:points to the last Node "" "Def __init__ (Self, item:object): Self.__item = Item Self.__next = None Self.__past = None @property def item (self): return Self.__item @item. Setter def item (SE LF, value): Self.__item = value @property def next (self): return Self.__next @next. Setter def NE XT (Self, value:object): Self.__next = value @property def past (self): return self.__past @past. Set ter def past (self, value:object): Self.__past = Valueclass linkedlist: "" "Description:base class Linked List "" "Def __init__ (self): Self.cur = None Self.head = None Self.length = 0 def append (sel F, No:object): Raise Exception (' base method ') def iternodes (self): Raise Exception (' base method ') def Pop (self): raise Exception (' base method ') def insert (self, position:int, value:object): Raise Exception (' base method ') def Remove (self, value:object): Raise Exception (' Base Method ') class Singlelinkedlist (LinkedList): "" "Descriptio N:attr head:head Node attr cur:current node method append (): Append Node "" "Def __init__ (self): Super (). __init__ () def __iter__ (self): Cur_node = Self.head while True:yield Cur_node.item If not cur_node.next:break Cur_node = Cur_node.next def __getitem__ (self, item): Cur_node = Self.head If Isinstance (item, slice): Pass Else:for _ in range (item): Cur_node = Cur_node.next return Cur_node.item def __setitem__ (self, Key, value): Cur_ node = Self.head for _ in range (key): Cur_node = Cur_node.next Cur_node.item = value def appen D (Self, no:object): if self.length = = 0:self.cur = Node (no) Self.head = Self.cur ELSE:SELF.CUR.N ext = Node (no) Self.cur = self.cur.next Self.length + = 1SL = Singlelinkedlist () sl.append (1) sl.append (2) F Or I in Sl:print (i) sl[1] = 999sl[0] = 234for i in Sl:print (i) class Doublelinkedlist (LinkedList): "" "Descrip Tion:attr head:attr cur:method append:method pop:method insert:method remove:method iternodes: "" "Def __init__ (self): Super (). __init__ () def __iter__ (self): Cur_node = Self.head while T Rue:yield Cur_node.item if not cur_node.next:break Cur_node = CUR_NODE.N Ext def __reversed__ (self): Cur_node = self.cur while True:yield cur_node.item if Not cur_node.past:break Cur_node = Cur_node.past def __getitem__ (self, item): Cur_nod E = Self.head IfIsinstance (item, slice): Pass Else:for _ in range (item): Cur_node = Cur_node. Next return Cur_node.item def __setitem__ (self, Key, value): Cur_node = Self.head for _ in ran GE (key): Cur_node = Cur_node.next Cur_node.item = value def append (self, no:object): if self. Length = = 0:self.cur = Node (no) Self.head = self.cur Else:temp = self.cur Self.cur.next = Node (no) self.cur = self.cur.next Self.cur.past = Temp Self.length + = 1 def pop (self): Pop_node = self.cur Pop_node.past.next = None self.cur = Self.cur.past self. Length-= 1 return pop_node def insert (self, position:int, value:object): Cur_node = self.head n Ew_node = node (value) for _ in range (position-1): Cur_node = Cur_node.next Next_node = Cur_node . Next Cur_node.neXT = New_node New_node.past = Cur_node New_node.next = Next_node next_node.past = New_node def rem Ove (self, value:object): Cur_node = Self.head while true:if Cur_node.item = = value: Cur_node.past.next = Cur_node.next Cur_node.next.past = Cur_node.past break E Lif not cur_node.next:raise Exception (' nodenotfound ') Cur_node = Cur_node.next def iternodes (Self, *, reverse=false): if isn't reverse:cur_node = Self.head while True:yie LD Cur_node.item if not cur_node.next:break Cur_node = Cur_node.next Else:cur_node = Self.cur while True:yield Cur_node.item if not C Ur_node.past:break Cur_node = Cur_node.past
Exception handling Create an exception
raise 异常实例
- The Python interpreter detects the exception itself and throws it
Exception capture
try:待捕获异常的代码块except [异常类型] as e:异常的处理代码块else:...finally:...
- E is an instance of an exception
- can write multiple except
- Else no exception occurred then execute
- Finally statement blocks are executed anyway
Baseexception
- Base class for all built-in exception classes
Systemexit
- Sys.exit () exception thrown, exception not captured processing, directly to the Python interpreter, interpreter exited
Keyboardinterrupt
- command line using CTRL + C terminal operation
Exception
- Base class for all built-in, non-system-exited exceptions, custom exceptions need to inherit it
SyntaxError syntax error
- This error is not captured
Arithmeticerror
- Arithmetic calculation error, subclass has except 0 exception etc.
Lookuperror
- The base class of the exception that is thrown when the index of a mapped key or sequence is not valid: Indexerror,keyerror
Modular Import ... With import ... as ...
From ... import ... With from ... import ... as ...
- The module name specified after from is only loaded and initialized, not imported
- For the name after the import clause
- Check that the From Import module has the Name property, and if it is not, try importing a submodule of that name
Custom Modules
- Naming conventions
- All lowercase, underline to split
Module Search Order Sys.path
- Return to List
- Can be modified to append a new path
Path Lookup Order
- Program Home Directory
- Pythonpath Directory
- Standard library Catalog
Sys.modules
- Back to Dictionary
- Log all loaded modules
Module operation
name
- The module name, if not specified, is the file name
- The interpreter initializes the Sys.module dictionary, creates the Builtins module, themain module, the SYS module, Sys.path
If
name= = '
Main‘
- For module function testing
- Avoid side effects of main module changes
Properties of the module
- File Source files path
- cached compiled byte-code file path
- Spec Display module specification
- Name Module name
- Package When the module is the same name, otherwise it can be set as the empty string of the top-level module
Package Packages
- There is an init. py file in the directory, and when the package is imported, the contents of this file represent this package
Sub-module
- The PY files and subdirectories in the package directory are all its sub-modules
Module and Package Summary
- Import submodule must load parent module, import parent module must not import submodule
A package is a special module that contains the path property
Absolute import, relative import absolute Import
- Always go to search the module search path to find
Relative import
- Can only be used within the package and can only be used in the From
- . Represents the current directory
- .. Represents the previous level of the directory
- ... Indicates Upper parent directory
Access control
From ... import *
- When you import a module using this method, properties that begin with _ and __ are not imported
- Use All
- A list, each element is a variable name within a module
- After you define all, the From ... import * only imports properties within all
Package Management
Setuptools
- Core modules for package management
Pip
- The current standard of fact for package management
- Wheel
- Binary installation, no local compilation required
pip install wheel
Create a setup.py file
# from distutils.core import setup # 可能失败from setuptools import setupsetup(name=‘Distutils‘, version=‘1.0‘, description=‘Python Distribution Utilities‘, author=‘Greg Ward‘, author_email=‘[email protected]‘, url=‘https://www.python.org/sigs/distutils-sig/‘, packages=[‘distutils‘, ‘distutils.command‘], )
- Package contents are packages to manage
Query command Help
python setup.py cmd -help
Build
python setup.py build
- Build files, and copy them directly to other projects to get the
Install
python setup.py install
- If there is no build, the build is compiled first and then installed
Sdist
python setup.py sdist
- Create a bundle of source code
- Unzip the file elsewhere, with setup.py in it, you can use the Python setup.py install installation, or you can
- Pip Install Xxx.zip directly installs this package with PIP
Plug-in development Dynamic Import
- runtime, according to user needs, find the resources of the module dynamically loaded up
- Import (Name, Globals=none, Locals=none, fromlist= (), level=0)
- Name Module name
- Import essentially calls this function (sys = impot(' sys ') equivalent to the import sys), but is not recommended for direct use, it is recommended to use
- Importlib.import_module (name, Package=none)
- Absolute and relative imports are supported, and in the case of relative imports, the package must be set
technologies that plug-in programming technology relies on
- Reflection: Runtime Gets the type of information that can be dynamically maintained for type data
- Dynamic import: Using importlib
- Multithreading: You can open a thread that waits for user input to load a module of the specified name
Loading time
- When the program starts
- Program in operation
- such as too many plug-ins, will cause the program to start very slowly, if the user needs to load again, if the plug-in is too large or dependent, the plug-in will start slowly.
- So first load must, common plug-ins, other plug-ins when used, found that need, dynamic loading
Basic Knowledge Supplement
Slots
- In order to query efficiency, the dictionary must use space to change time
- If the number of instance objects is too large, the dictionary takes up too much space
- If the class defines a slot, the instance omits the build dict
- If adding a property that is not in the slot to an instance throws a attribute exception
- slots can be defined as tuples or lists, typically with tuples, saving space
- slots do not inherit to subclasses
Not implemented and not implemented exceptions
- Notimplemented is a value, single value, is an instance of the Notimplementedtype class
- Notimplementederror is a type, is an exception, returns the type
Inverse method in operator overloading
- Call the reverse method when the forward method returns notimplemented
Git Server Setup Gogs Software Dependencies
Mysql
Installation
useradd gitsu - gittar xf gogs*cd gogsmysql -uroot -p < scripts/mysql.sql
grant all on gogs.* to ‘gogs‘@‘%‘ identified by ‘gogs‘;flush privileges;
Configuration file
mkdir -p custom/confcd custom/conftouch app.ini
Start Gogs
./gogs Web
- Service startup
Log directory needs to be established under Gogs
Root User Action
cp /home/git/gogs/scripts/init/centos/gogs /etc/init.d/chmod +x /etc/init.d/gogschkconfig gogs onservice gogs start
First Login
Http://IP:Port/install
Python Nineth Week Study notes (1)