Directory:
- Module additions
- Xml
- Object oriented
one, Module Supplement
Shutil: file copy module, file copy, compress, use method: Copy the contents of the file to another file, you can part of the content shutil.copyfileobj (fsrc,fdst[,length]) #文件对象; Open the file before copy; Import SHUTILF = open (' example.log ') f2 = open (' example_new.log ', ' W ') shutil.copyfileobj (f,f2) shutil.copyfile (src, DST Copy files directly to copy file name; shutil.copyfile (src,dst) shutil.copyfile (' example_new.log ', ' Example_new2.log ') shutil.copymode ( Str,dst) only copy permissions, content, user and Group are unchanged, shutil.copymode (' example_new.log ', ' example_new2.log ') shutil.copystat (src, dst) copy State information, Includes: mode bits, atime, mtime, flagsshutil.copy (src, dst) copy files and permissions shutil.copy2 (src, dst) copy files and status information Shutil.ignore_patterns (* Patterns) shutil.copytree (src, dst, symlinks=false, ignore=none) recursively de-copying files such as: copytree (source, destination, ignore= Ignore_patterns (' *.pyc ', ' tmp* ')) shutil.rmtree (path[, ignore_errors[, onerror]) recursively remove files Shutil.move (src, dst) Recursive go-to-move file shutil.make_archive (base_name, format,...) Create a compressed package and return the file path, for example: zip, tarbase_name: The file name of the compressed package, or the path to the compressed Package. is only the file name, save to the current directory, otherwise save to the specified path, such as: www. = Save to the current path such as:/users/wupeiqi/www = Save To/users/wupeiqi/format: package type, "zip", "taR "," Bztar "," gztar "root_dir: folder path to compress (default current Directory) owner: user, default Current user group: groups, default current group logger: used for logging, usually logging. Logger Object example: file packaging under #将/users/wupeiqi/downloads/test to place the current program directory import Shutilret = shutil.make_archive ("wwwwwwwwww", ' Gztar ', root_dir= '/users/wupeiqi/downloads/test ') #将/users/wupeiqi/downloads/test file package to place/users/wupeiqi/directory Import Shutilret = shutil.make_archive ("/users/wupeiqi/wwwwwwwwww", ' gztar ', root_dir= '/users/wupeiqi/downloads/test ') Example: Import zipfile# Compression z = zipfile. ZipFile (' laxi.zip ', ' W ') z.write (' a.log ') z.write (' data.data ') z.close () # unzip z = zipfile. ZipFile (' laxi.zip ', ' r ') z.extractall () z.close () example: import tarfile# Compress tar = tarfile.open (' your.tar ', ' W ') tar.add ('/ Users/wupeiqi/pycharmprojects/bbs2.zip ', arcname= ' bbs2.zip ') tar.add ('/users/wupeiqi/pycharmprojects/cmdb.zip ', Arcname= ' Cmdb.zip ') tar.close () # Unzip tar = tarfile.open (' your.tar ', ' r ') tar.extractall () # can set decompression address Tar.close () Shutil The processing of the compressed package is called ZipFile and tarfile two modules, detailed: packaging: file name plus date can be self-splicing; shutil.make_archive (' day5 ', ' Zip ', ' C:\\users\administraTor\s16\day5 ') is similar to json, which is a protocol for the exchange of data between a language or a program; the format of XML is as follows: the structure is distinguished by the <> node; <data><country name= " Liechtenstein "><rank updated=" Yes ">2</rank><year>2008</year><gdppc>141100</ Gdppc><neighbor name= "Austria" direction= "E"/><neighbor name= "switzerland" direction= "W"/></ Country></data>xml processing: The XML protocol is supported in each language and can be manipulated in Python using the following modules XmlImport Xml.etree.ElementTree as Ettree = Et.parse (' xmltest.xml ') #解析root = tree.getroot () print (root.tag) print (dir (root)) traverses the XML document: for child in Root:print (child Tag,child.attrib) for I in Child:print (i.tag,i.text,i.attrib) traverses only the year node, and for node in Root.iter (' year ') print (node.tag, Node.text) only traverse the country node: for node in root.iter (' year ') print (node.tag, node.text, node.attrib) modify: for node in Root.iter (' YESR '): new_year = int (node.text) + 1node.text = str (new_year) node.set ("updated", "yes") tree.write ("xmltest.xml") Delete Nodefor country in Root.findall (' country '): rank = int (country.find (' rank '). Text) if rank > 50:root. Remove (country) tree.write (' output.xml ', encoding= ' utf-8 ') hashlib:hash encryption module; HMAC module: mainly used for message authentication in the internet; hash message identification code, or HMAC , is a kind of authentication mechanism based on the message identification code MAC (messages authentication code). When using hmac, both sides of the message communication can authenticate the authenticity of the message by verifying the authentication key K which is added in the Message. generally used in network communication message encryption, The premise is that both parties must first agree a good key, like a connector password, and then send the message to use key to encrypt messages, the receiver with key + message plaintext again encrypted, The relative ratio of the encrypted value to the sender is equal, which verifies the authenticity of the message and the legitimacy of the sender. Subprocess:import subprocesssubprocess.run (["df", '-h '],returncode=1) #自动拼接并输出; subprocess.run (["df", "-h", "|", " grep ","/dev/sda1 "]) #有管道会报错; subprocess.run (" df-h | GREP/DEV/SDA1 ", Shell=true) #shell =true means calling the shell directly without parsing the execution command, returning the command execution state, 0 or non-0subprocess.call (" df-h | GREP/DEV/SDA1 ", Shell=true) receives the string format command, returns a tuple form, the 1th element is the execution state, and the 2nd is the command result; ba = subprocess.getstatusoutput (" df-h | GREP/DEV/SDA1 ") run, shell=truecallcheck_callgetstatusoutputp = Popen () stdout = subprocess. PIPE, stderr = .... env = {} #后跟字典; CWD = {}prexec_fn =p.stdout.read () p.poll () p.wait () p.communicate (timeout=3) re: Regular expression ; Re.match ("al", "alex Li") #前面是规则, followed by a string to match; <_sre. Sre_match object; span= (0, 2), match= ' al ' >a = RE.MATCH ("^.+", "alex\n Li") a.group () #可打印匹配到的值; re.search ("i$", "alex\n Li") re.match: match from the beginning, re.search: match whole line; Re.findall (' \w+ ', ' 192.168.0.23 ') re.split (' \w+ ', ' 192.168.0.23 ') re.sub match and replace; re.sub (' \d{4} ', ' 1987 ', ' I was born in 1996-05-23,ys are 1919 ', Count=1) #默认会全部替换; count specifies how many times to replace; ' I was born in 1987-05-23,ys is 1919 ' >>> re.search (r "\root\\", "\root\\ Alex\test ") <_sre. Sre_match object; span= (0, 5), match= ' \root\\ ' > '. ' default match any character except \ n, If flag Dotall is specified, matches any character, including the newline ' ^ ' match character beginning, if the flags MULTILINE is specified, This can also be matched on (r "^a", "\nabc\neee", flags=re. MULTILINE) ' $ ' matches the end of the character, or E.search ("foo$", "bfoo\nsdfsf", flags=re. MULTILINE). group () can also ' * ' match the character before the * number 0 or more times, re.findall ("ab*", "cabb3abcbbac") result for [' ABB ', ' ab ', ' a '] ' + ' matches the previous character 1 or more times, Re.findall ("ab+", "ab+cd+abb+bba") Results [' ab ', ' ABB '] '? ' match the previous character 1 or 0 times ' {m} ' matches the previous character m Times ' {n,m} ' matches the previous character N to M times, re.findall ("ab{ 1,3} "," ABB ABC abbcbbb ") results ' ABB ', ' ab ', ' ABB ' ' | ' match | left or | right character, re.search (" abc| ABC "," ABCBABCCD "). group () results ' ABC ' (...) ' grouping matches, re.search (" (ABC) {2}a (123|456) c "," abcabca456c "). group () results ABCABCa456c ' \a ' matches only from the beginning of the character, re.search ("\aabc", "alexabc") is not matched to the ' \z ' match character end, the same as $ ' \d ' matches the number 0-9 ' \d ' matches the Non-numeric ' \w ' match [a-za-z0-9] ' \w ' matches the non-[ A-za-z0-9] ' s ' matches whitespace characters, \ t, \ n, \ r, re.search ("\s+", "ab\tc1\n3"). group () result ' \ t ' (? p<name>, ...) ' Group Matching Re.search (? P<province>[0-9]{4}) (? P<city>[0-9]{2}) (? P<birthday>[0-9]{4}) "," 371481199306143242 "). groupdict (" City ") result {' province ': ' 3714 ', ' city ': ' Bayi ', ' birthday ' : ' 1993 '}
third, object-oriented
Features: encapsulation, inheritance, Polymorphism
Programming paradigm:
Programming is the process by which programmers use specific syntax + data structure + algorithms to tell a computer how to perform a task, and a program is a set of instructions that programmers write in order to get a task result, and there are many different ways to implement a Task. This paper summarizes the characteristics of these different programming methods, which is the programming paradigm;
Most languages support only one programming paradigm, and some languages can support multiple programming paradigms at the same time, and two of the most important programming paradigms are process-oriented and object-oriented programming;
Process Oriented:
Process-oriented programming Dependent process, a process consists of a set of steps to be computed, process-oriented is also known as Top-down languages;
Object-oriented:
OOP (object oriented Programing) programming uses "class" and "object" to create various models to realize the Real-world description;
Object-oriented benefits:
Can make the maintenance and expansion of the program easier, and can greatly improve the development efficiency of the program;
object-oriented programs make it easier for others to understand code logic;
Class:
A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties. The properties of these objects defined in the class (variables (data)), common methods;
Object Objects:
An instantiated instance of an object class; a class must be instantiated before it can be called in a program; a class can instantiate multiple objects, and each object can have different properties;
Encapsulation: Package
The assignment of the data in the class, the internal invocation is transparent to the external user, which makes the Class A capsule or container, with the data and methods of the class contained in the bread;
Inheritance: inheritance
A class can derive a subclass, a property defined in the parent class, a method that automatically inherits the quilt class;
Polymorphism: polymorphic
Python native is polymorphic, one interface, multiple implementations;
Example: class Dog: age = #类变量, where the memory address of the class exists and can be shared by all instances; def __init__ (self,name,type): #初始化函数 (constructor) self.name = name # D.name = Nameself.type = Type # D.type = typedef balk (self): # self = dprint (' [%s] I am a dog! ' %self.name) def eat (self,food):p rint ("[%s] eating [%s]"% (self,name,food)) d = Dog ("ys", "zang Ao") print (d.name, D.type) D.balk () d.eat (' sandwish ') d.name= ' ddd ' Print (d.name,d.age)
Packaging:
Encapsulation is one of object-oriented features, and is the main characteristic of object and class Concept.
Class Variables:
In the memory address of the existing class, the reference can be shared by all instances, and can be some common attributes;
Role:
As the default public property, static field;
Global modification or addition of new attributes;
Example: class people (object): nationality = "CN" def __init__ (self,name,age,job):p assp = people ("liuhao", +, ' IT ') p2 = people ( "yanshui", p.nationality = "JP" print (p.nationallity) P2.hobbie = "big baojian" people.weapon = "big baojian" # Add Global properties; Print (p.weapon)
Instance variable: (member Property)
As opposed to class variables, all objects inside the constructor are instance variables;
Each instance has its own properties in the memory space;
P2.hobbie = "Big baojian"
Public Attribute: = = "class variable;
Private Properties:
Attributes that do not want to be accessed by others;
__sex: represents a private property and can only be called within each function (method);
Hide some of the implementation details of the function, only to the external exposure call interface;
Inherited:
One of the main functions of object-oriented programming (OOP) language is inheritance, which can use all the functions of an existing class, and extend these functions without rewriting the original classes;
New classes created through inheritance are called "subclasses" or "derived classes";
The inherited class is called the "base class", "parent class" or "super class";
The process of inheritance is from the general to the special process;
Inheritance is implemented in two Ways:
Inherited
Combination
In some OOP languages, a subclass can inherit multiple base classes, in general, there can be only one base class for a subclass, and multiple inheritance can be realized by multilevel inheritance.
There are 2 main ways to implement the concept of inheritance:
Implementing inheritance
Refers to the ability to use the properties and methods of a base class without additional coding;
Note: the relationship between the two classes should be a "belongs" relationship;
Interface inheritance
Refers to the use of only the name of the property and method, but the subclass must provide the ability to implement (the subclass refactoring method of the parent class);
An abstract class is a parent class that defines only the generic properties and methods created by subclasses;
Example: class Schoolmember (object): members = 0def __init__ (self,name,age,sex): self.name = nameself.age = Ageself.sex = Sexschoolmember.members + = 1print ("initializes A new school member", self.name) def tell: info = "" "------info of%s---------name:% sage:%ssex:%s "" "% (self.name,self.name.self.age,self.sex) print (info) def __del__ (self): #析构方法: print ("%s dismissed "% Self.name) schoolmember.members-= 1class Teacher (schoolmember): #继承def __init__ (self,name,age,sex,salary): #手动调用父类方法 ; schoolmember.__init__ (self,name,age,sex,salary) #self. name = Name#self.age = Age#self.sex = Sexself.salary = Salarydef Teaching (self,course):p rint ("%s is teaching%s"% (self.name,self.course)) class Student (schoolmember):d EF __init__ ( Self,name,age,sex,grande) schoolmember.__init__ (self,name,age,sex,grande) self.grande = grandedef pay_tuition (self, amount): self.paid_tuition = Amountprint (' stduent%s has paid tutuion amount%s '% (self.name,amount)) t = Teacher ("Alex", 22 , "f", +) s = Student ("liuhao", "M", "pays16") s1 = Student ("yanshuai", "f", "p"Ys26 ") s2 = Student (' nining ', +, ' F ', ' pys26 ') del S2 #删除一个实例; t.tell () s.tell () s1.tell () t.teaching (" python ") s.pay_ Tuition (11000) Print (t.name) print (t.age) print (t.salary) print (schoolmember.members)
Inherited:
1, directly call the parent class method;
2, inherits the parent class method and reconstructs the parent class method, first reconstructs, then reconstructs the method to call the parent class method manually;
3, You can define the sub-class of their own methods;
4, The Destruction method;
Multiple inheritance:
generally, the maximum number of inherited two;
Example: class Course (object): course_name = "Python automation" period = "7m" Outline = "sfdskljjklfsdj" test = 321class Student (schoolme mber,course,my_teacher): test = 123def __init__ (self,name,age,sex,grande) schoolmember.__init__ (self,name,age,sex, Grande) Self.grande = grandeself.my_teacher =teacherdef pay_tuition (self,amount): self.paid_tuition = Amountprint (' stduent%s has paid tutuion amount%s '% (self.name,amount)) c = Course () #可达到构造函数效果; c.name = "Linux" s = Student ("liuhao", 24, "M", "pays16", T) s.my_new_teacher = tprint (s.course_name, s.outline) print (s.test) print ("my teacher", s.my_ Teacher.name)
Python module complements, object-oriented