This program is recorded:
1. Generator
1.1 List-derived methods
1.2 Function Method--application of complex derivation method
2. iterators
3, the decorative device
3.1 Single authentication method (call does not pass parameters)
3.2 Single authentication method (call pass parameter)
More than 3.3 kinds of authentication methods
4. Module
4.1 Third-party modules
4.2 Standard Library
4.3 sys module
5. JSON
5.1 JSON serialization
5.2 JSON deserialization
1. Generator
1.1 List-derived methods
data = [+ +]
data = (i*2 for i in data)
Print (data)
Print (data.__next__ ())
Print (data.__next__ ())
Print (data.__next__ ())
1.2 Function Method--application of complex derivation method
def fib (num):
Count = 0
A, B = 0,1
While Count < num:
TMP = a
A = b
b = A + tmp
#print (a)
Count + = 1
Yield a
Print ("Done ...")
num = Int (input ("NUM>>:")) #输入打印的数据数量
f = fib (num)
For I in range (num):
Print (f.__next__ ())
****************************************************
In the function:
Return a returns a, and ends the function
Yield a returns a and suspends the function, returning to the person who invokes the function through __next__ ();
Represents the break of a function through yield and holds the intermediate state of the function execution.
Simulate Concurrency:
Import time
DEF consumer (name):
Print ("%s ready to eat Buns"% name)
While True:
Baozi = yield
Print ("Bun [%s] came, was [%s] eaten"% (baozi,name))
def producer (name):
C1 = Consumer ("A")
C2 = Consumer ("B")
C1.__next__ ()
C2.__next__ ()
Print ("%s made Buns"% name)
For I in range (5):
Time.sleep (1)
Print ("Make 2 Buns")
C1.send (i+1)
C2.send (i+1)
Producer ("Tom")
****************************************************
2. iterators
Can be called by the next () function and continually return a worthy object to become an iterator
Generators are iterators >>> generators are iterators with the next method that can only iterate once
Iterators are not all generators
The object generated by ITER is an iterator, or it can be said to be a generator
(1), ITER independent generation iterator, this angle can say iterators and generators are not the same
(2), the bottom of the ITER is also an iterator generated by the generator method, which can be said that iterators and generators like
Range function Optimization
Py2 directly generate the corresponding list
Py3 generating the corresponding generator
****************************************************
3, the decorative device
Higher-order function nesting functions--adds new functionality to the original code, but does not change the original code
Role:
Fully conform to the principle of openness and closure-do not change the original code, call mode, to achieve functional expansion
3.1 Single authentication method (call does not pass parameters)
User_status = False
def login (func):
def inner ():
_username = ' Zs '
_PASSWD = ' 123 '
Global User_status
if User_status = = False:
Username = input ("USER>>:")
passwd = input ("PW>>:")
If username = = _username and passwd = = _passwd:
Print ("welcome!")
User_status = True
Else
Print ("Wrong username or passwd")
If User_status:
Func ()
return inner
Def home ():
Print ("Home")
@login
Def America ():
#login ()
Print ("United States")
@login
DEF Japan ():
#login ()
Print ("Japan")
Def China ():
Print ("China")
Home ()
#america = Login (America)
America ()
#japan = login (Japan)
Japan ()
China ()
3.2 Single authentication method (call pass parameter)
User_status = False
def login (func):
def inner (*args,**kwargs):
_username = ' Zs '
_PASSWD = ' 123 '
Global User_status
if User_status = = False:
Username = input ("USER>>:")
passwd = input ("PW>>:")
If username = = _username and passwd = = _passwd:
Print ("welcome!")
User_status = True
Else
Print ("Wrong username or passwd")
If User_status:
Func (*args,**kwargs)
return inner
Def home ():
Print ("Home")
@login
Def America (Stype):
Print (Stype)
Print ("United States")
DEF Japan ():
Print ("Japan")
Def China ():
Print ("China")
Home ()
America (' America ')
Japan (' Japan ')
China ()
More than 3.3 kinds of authentication methods
User_status = False
def login (stype):
def outer (func):
def inner (*args,**kwargs):
if stype = = ' QQ ':
_username = ' Zs '
_PASSWD = ' 123 '
Global User_status
if User_status = = False:
Username = input ("USER>>:")
passwd = input ("PW>>:")
If username = = _username and passwd = = _passwd:
Print ("welcome!")
User_status = True
Else
Print ("Wrong username or passwd")
If User_status:
Func (*args,**kwargs)
Else
Print ("QQ only authentication supported")
return inner
return outer
Def home ():
Print ("Home")
@login (' QQ ')
Def America (Stype):
Print (Stype)
Print ("United States")
@login (' Weixin ')
DEF Japan ():
Print ("Japan")
Def China ():
Print ("China")
Home ()
America (' America ')
Japan (' Japan ')
China ()
4. Module
Import Sys
For I in Sys.path:
Print (i)
Output:
D:\python Training \our_python\day5
D:\python Training \our_python
F:\Python\Python3\python35.zip
F:\Python\Python3\DLLs
F:\Python\Python3\lib
F:\Python\Python3
F:\Python\Python3\lib\site-packages
Find the module in accordance with the above-mentioned path in turn to query, know that the module, or error
__FILE__ Take relative path
Os.path.abspath (__file__) changes the relative path to an absolute path
Multiple module import, one line per module, too long module name alias
Py2
There is no __init__ in the directory, it is just a directory, the directory is not allowed to be imported
__init__ in the directory, this directory becomes a "package" =package package is a collection of modules
Py3
4.1 Third-party modules
PyPI URL on pip installation
4.2 Standard library
OS Module
OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work
Os.chdir ("dirname") changes the current script working directory, equivalent to the shell CD
Os.curdir returns the current directory: ('. ')
Os.pardir Gets the parent directory string name of the current directory: (' ... ')
Os.makedirs (' dirname1/dirname2 ') can generate multi-level recursive directories
Os.removedirs (' dirname1 ') if the directory is empty, then delete, and recursively to the previous level of the directory, if also empty, then delete, and so on
Os.mkdir (' dirname ') generates a single-level directory, equivalent to mkdir dirname in the shell
Os.rmdir (' dirname ') delete the single-level empty directory, if the directory is not empty can not be deleted, error, equivalent to the shell rmdir dirname
Os.listdir (' dirname ') lists all files and subdirectories in the specified directory, including hidden files, and prints as a list
Os.remove () Delete a file
Os.rename ("Oldname", "newname") renaming files/directories
Os.stat (' path/filename ') get File/directory information
OS.SEP output operating system-specific path delimiter, win under "\ \", Linux for "/"
OS.LINESEP output The line terminator used by the current platform, win under "\t\n", Linux "\ n"
OS.PATHSEP output string for splitting the file path
The Os.name output string indicates the current usage platform. Win-> ' NT '; Linux-> ' POSIX '
Os.system ("Bash command") runs a shell command that directly displays
Os.environ Getting system environment variables
Os.path.abspath (path) returns the absolute path normalized by path
Os.path.split (path) splits path into directory and file name two tuples returned
Os.path.dirname (path) returns the directory of path. is actually the first element of Os.path.split (path)
Os.path.basename (Path) returns the last file name of path. If path ends with a/or \, then a null value is returned. The second element of Os.path.split (path)
Os.path.exists (path) returns true if path exists, false if path does not exist
Os.path.isabs (path) returns True if path is an absolute path
Os.path.isfile (path) returns True if path is a file that exists. otherwise returns false
Os.path.isdir (path) returns True if path is a directory that exists. otherwise returns false
Os.path.join (path1[, path2[, ...]) returns a combination of multiple paths, and the parameters before the first absolute path are ignored
Os.path.getatime (Path) returns the last access time of the file or directory to which path is pointing
Os.path.getmtime (Path) returns the last modified time of the file or directory to which path is pointing
4.3 sys module
SYS.ARGV command line argument list, the first element is the path of the program itself
Sys.exit (n) exit program, Exit normally (0)
Sys.version get version information for Python interpreter
Sys.maxint the largest int value
Sys.path returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing
Sys.platform returns the operating system platform name
Sys.stdout.write (' please: ')
val = Sys.stdin.readline () [:-1]
Progress bar:
Import sys, TIME
For I in range (5):
Sys.stdout.write (' # ')
Time.sleep (1)
Sys.stdout.flush ()
5. JSON
The form of converting a memory object into a string is serialized
Turning a character into a corresponding memory object is an inverse sequence.
Serialization persistence of memory data
Json.dumps (data) for serialization
Json.loads (F.read ()) for data serialization
Json.dump (data) for serialization
Json.load (F.read ()) for data serialization
5.1 JSON serialization
<1>
Import JSON
data = {' name ': ' Zs ', ' Age ': 26}
f = open (' Json.txt ', ' W ', encoding= ' utf-8 ')
F.write (Json.dumps (data))
F.close ()
<2>
Import JSON
data = {' name ': ' Zs ', ' age ': +, ' sex ': ' Men '}
f = open (' Json.txt ', ' W ', encoding= ' utf-8 ')
Json.dump (DATA,F)
F.close ()
5.2 JSON deserialization
<1>
Import JSON
f = open (' Json.txt ', ' R ', encoding= ' utf-8 ')
data = Json.loads (F.read ())
Print (data)
Print (data[' age ')
<2>
Import JSON
f = open (' Json.txt ', ' R ', encoding= ' utf-8 ')
data = Json.load (f)
Print (data)
Print (data[' age ')
JSON takes data from a file, only takes one type, and only goes to one record, that is, dump and load can only be 1 times.
JSON cannot serialize functions---all languages are common
Pickle is only used in the Python language to support planning for all data types
Python Foundation article-day5