程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Advanced usage of Python function definitions

編輯:Python

Several kinds of common parameters in function definition :

1、 Default parameters

Look at the code below

def stu_register(name,age,country,course):
print("---- Registration ⽣ Health information ------")
print(" full name :",name)
print("age:",age)
print(" nationality :",country)
print(" Course :",course)
stu_register(" king ⼭ Mountain cannon ",22,"CN","python_devops")
stu_register(" Zhang Jiaochun ",21,"CN","linux")
stu_register(" Liu ⽼ Old roots ",25,"CN","linux")

Find out country This parameter Basically all yes ”CN”, It's like we're here ⽹ Sign up for ⽤ user , Information like nationality , If you don't fill in , Default It would be China , This is done with default parameters , hold country Become the default parameter ⾮ It's simple

def stu_register(name,age,course,country="CN"):

such , This parameter is being adjusted ⽤ Time is not specified , The default is CN, If specified , Just ⽤ Use the value you specify .

in addition , You may have noticed , In the country When it becomes the default parameter , At the same time, I moved its position to the last ⾯ Noodles , Why? Well ?
This is grammatically mandatory , The default parameter is placed after other parameters , Why? ? Suppose this is allowed :

def stu_register(name,age,country="CN",course):

That tune ⽤ when

stu_register("Mack",22,"Python","US")

You told me , The first 3 Parameters python In the end, it should be given country still course Well ? ⽆ No matter which one you give , There will be ambiguity , therefore Python grammar ⼲ Simply let you put the default parameters last , When the interpreter deals with the parameters of a function , By priority , Positional arguments > Default parameters .

Two 、 The key parameters ( Specify the parameters )

Under normal circumstances , Pass parameters to functions in order , No, just in order ⽤ Use key parameters , Just specify the parameter name ( Parameters are specified The parameter named is called the key parameter ), But remember ⼀ One requirement is , The key parameters Must be on Positional arguments ( Determine the parameters of the corresponding relationship in the order of position ) after .


def stu_register(name, age, course='PY' ,country='CN'):
print("---- Registration ⽣ Health information ------")
print(" full name :", name)
print("age:", age)
print(" nationality :", country)
print(" Course :", course)

transfer ⽤ It can be used like this ( The correct way to call :

stu_register(" king ⼭ Mountain cannon ",course='PY', age=22,country='JP' )

But never

stu_register(" king ⼭ Mountain cannon ",course='PY',22,country='JP' )

Of course, this is not ⾏

stu_register(" king ⼭ Mountain cannon ",22,age=25,country='JP' )

This is equivalent to giving age assignment 2 Time , Will report a mistake !
Be careful , The priority order of parameters is Positional arguments > The key parameters

3、 ... and 、⾮ Fixed parameter

If your function is defined indefinitely ⽤ The user wants to send ⼊ Enter how many parameters , You can make ⽤ use ⾮ Fixed parameter

def stu_register(name,age,*args): # *args Will pass more ⼊ The input parameter becomes ⼀ A tuple form 
print(name,age,args)
stu_register("Alex",22)
# Output 
#Alex 22 () # after ⾯ Face this () Namely args, Just because there's no passing value , So it's empty 
stu_register("Jack",32,"CN","Python") # Output 
# Jack 32 ('CN', 'Python')

You can also have ⼀ individual **kwargs

def stu_register(name,age,*args,**kwargs): # *kwargs Will pass more ⼊ The input parameter becomes ⼀ One dict shape type 
print(name,age,args,kwargs)
stu_register("Alex",22)
# Output 
#Alex 22 () {}# after ⾯ Face this {} Namely kwargs, Just because there's no passing value , So it's empty 
stu_register("Jack",32,"CN","Python",sex="Male",province="ShanDong") # Output 
# Jack 32 ('CN', 'Python') {'province': 'ShanDong', 'sex': 'Male'}

1.5 Local variables and global variables

Look at the code below

name = "Alex Li" def change_name():
name = " gold ⻆ King , ⼀ a Tesla Senior loser " print("after change", name)
change_name() print(" Look outside name Have you changed ?",name)
# Output 
>>>
after change ⾦⻆ King ,⼀ a Tesla Senior loser Outside ⾯ see name Have you changed ? Alex Li

Why is it changed inside the function name After the value of , outside print I didn't change it when I was ? Because these two name Not at all ⼀ What's going on

  • Variables defined in a function are called local variables , In the process of ⼀ The variables that are initially defined are called global variables .
  • Global variable scope ( That is, the effective range ) It's the whole program , Local variables do ⽤ A field is a function that defines the variable .
  • The search order of variables is local variables > Global variables ;
  • When a global variable has the same name as a local variable , In a function that defines a local variable , Local variables act ⽤; In other places ⽅ The square global variable measures ⽤.
  • In function ⾥ You cannot directly modify global variables .

Just want to be in the function ⾥ How to modify the global variable quantity inside ?

name = "Alex Li"
def change_name():
global name # Statement ⼀ A global variable 
name = "Alex ⼜ also called ⾦ Gold and gold ⻆ horn ⼤ King , Love ⽣ life 、 Love ⾃ free 、 Love girls "
print("after change",name)
change_name()
print(" Outside ⾯ Have a look name Have you changed ?", name)

global name Works of ⽤ That is, in the function ⾥ Declare global variables name , It means top ⾯ Of name = “Alex Li” Even if you don't write , The last part of the program print You can also print name. Although it can be changed , But it is not recommended ⽤ This global grammar , As the code grows , It will make code debugging difficult .

1.6 Built in functions

The operation of each function ⽤ I marked it for you

1. abs # Find the absolute value 
2. all #Return True if bool(x) is True for all values x in the iterable.If the iterable is empty, return
True.
3. any #Return True if bool(x) is True for any x in the iterable.If the iterable is empty, return
False.
4. ascii #Return an ASCII-only representation of an object,ascii(“ China ”) return ”‘\u4e2d\u56fd’”
5. bin # Returns the of an integer 2 Base format 
6. bool # Judge ⼀ A data structure is True or False, bool({}) Return is False, Because it's empty dict
7. bytearray # hold byte become bytearray, Modifiable array 
8. bytes # bytes(“ China ”,”gbk”)
9. callable # Judge ⼀ Whether an object is adjustable ⽤ use 
10. chr # return ⼀ A number corresponds to ascii character , ⽐ such as chr(90) return ascii⾥ Inside ’Z’
11. classmethod #⾯ Object oriented ⽤ use , Now ignore 
12. compile #py Interpreter ⾃ since ⼰ Oneself ⽤ Used East ⻄ In the west , Ignore 
13. complex # Find the complex number ,⼀ commonly ⼈ people ⽤ Can't use 
14. copyright # no ⽤ use 
15. credits # no ⽤ use 
16. delattr #⾯ Object oriented ⽤ use , Now ignore 
17. dict #⽣ Generate ⼀ An empty dict
18. dir # Returns the tunability of the object ⽤ Use attributes 
19. divmod # Returns the quotient and remainder of division ,⽐ such as divmod(4,2), result (2, 0)
20. enumerate # Return the index and elements of the column list ,⽐ such as d = [“alex”,”jack”],enumerate(d) after , obtain (0, ‘alex’)
(1, ‘jack’)
21. eval # You can string characters list,dict,set,tuple, Then convert to its original data type .
22. exec # Put the code in string format , Into the ⾏ Act, interpret and uphold ⾏ Line line ,⽐ such as exec(“print(‘hellworld’)”), Understand meaning ⾥ Li Li ⾯ The character of the face 
Serial parallel execution ⾏ Line line
23. exit # Exit procedure 
24. filter # Yes list、dict、set、tuple Wait for the iteratable object to enter ⾏ Line by line filtering , filter(lambda x:x>10,
[0,1,23,3,4,4,5,6,67,7]) Filter out all ⼤ Greater than 10 Value
25. float # Convert to floating point 
26. format # no ⽤ use 
27. frozenset # hold ⼀ A set becomes immutable 
28. getattr #⾯ Object oriented ⽤ use , Now ignore 
29. globals # Print the whole picture ⽤ Use domain ⾥ The value in 
30. hasattr #⾯ Object oriented ⽤ use , Now ignore 
31. hash #hash function 
32. help
33. hex # return ⼀ One 10 It's binary 16 The hexadecimal representation ,hex(10) return ’0xa’
34. id # View the memory address of the object 
35. input
36. int
37. isinstance # Judge ⼀ The type of a data structure ,⽐ For example, judgment a Isn't it fronzenset, isinstance(a,frozenset) return 
return True or False
38. issubclass #⾯ Object oriented ⽤ use , Now ignore 
39. iter # hold ⼀ A data structure becomes an iterator , After talking about iterators, it's clear ⽩ It's white 
40. len
41. list
42. locals
43. map # map(lambda x:x**2,[1,2,3,43,45,5,6,]) Output [1, 4, 9, 1849, 2025, 25, 36]
44. max # Seeking the best ⼤ Great value 
45. memoryview # ⼀ commonly ⼈ People are not ⽤ use , Ignore 
46. min # Seeking the best ⼩ Small value 
47. next # ⽣ The generator will ⽤ be used , Now ignore 
48. object #⾯ Object oriented ⽤ use , Now ignore 
49. oct # return 10 Of a decimal number 8 Hexadecimal said 
50. open
51. ord # return ascii The character corresponding to 10 Hexadecimal number ord(‘a’) return 97,
52. print
53. property #⾯ Object oriented ⽤ use , Now ignore 
54. quit
55. range
56. repr # Nothing ⽤ use 
57. reversed # You can put ⼀ A column list is inverted 
58. round # You can put ⼩ decimal 4 House 5⼊ Rounded to an integer ,round(10.15,1) have to 10.2
59. set
60. setattr #⾯ Object oriented ⽤ use , Now ignore 
61. slice # no ⽤ use 
62. sorted
63. staticmethod #⾯ Object oriented ⽤ use , Now ignore 
64. str
65. sum # Sum up ,a=[1, 4, 9, 1849, 2025, 25, 36],sum(a) have to 3949
66. super #⾯ Object oriented ⽤ use , Now ignore 
67. tuple
68. type
69. vars # return ⼀ The properties of an object ,⾯ Object-oriented is clear ⽩ It's white 
70. zip # You can put 2 Put together one or more column lists ⼀ One , a=[1, 4, 9, 1849, 2025, 25, 36],b = [“a”,”b”,”c”,”d”],
list(zip(a,b)) # Get results [(1, 'a'), (4, 'b'), (9, 'c'), (1849, 'd')]

1.7 Module leads to ⼊ Enter into & transfer ⽤ use

There are several import modules ⽅ The way :

import module_a # guide ⼊
from module import xx # Import a... Under a module ⽅ Law or ⼦ modular 
from module.xx.xx import xx as rename # guide ⼊ after ⼀ individual ⽅ Repeat the order after the law 
from module.xx.xx import * # guide ⼊⼀ All modules ⽅ Law , It is not recommended to make ⽤
module_a.xxx # transfer ⽤

Be careful : modular ⼀ Dan was transferred ⽤, It is equivalent to holding ⾏ In addition ⼀ individual py⽂ file ⾥ Code for .

1.8 ⾃ Define modules

This is the easiest one , establish ⼀ individual .py⽂ file , It can be called a module , In another program ⾥ guide ⼊.

1.9 Module search path

Did you find ,⾃⼰ The written module can only be imported in the program under the current path ⼊, Import another directory ⼊ Your module reports an error . Said I couldn't find it , Why is that ? This is related to guidance ⼊ The search path of the module is related .

import sys
print(sys.path)

Output ( Note that different computers may output different ⼀ equally )


['', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages']

You import ⼀ Module time ,Python The interpreter will follow ⾯ List in order to each ⽬ Record it to match your guide ⼊ Module name of , As long as ⼀ individual ⽬ The module name is matched under the directory , Just ⽴ Carve Guide ⼊ Enter into , No more looking back .
Pay attention to number ⼀ Elements are empty , Represents the current ⽬ record , So you ⾃ The defined modules will be preferentially imported in the current directory ⼊ Enter into .
We are from ⼰ If you want to create a module anywhere ⽅ Can call , Then make sure your module ⽂ Pieces of ⾄ Less in the lookup list of the module path .
We ⼀ General self ⼰ The written module is placed in ⼀ One with “site-packages” Wording ⽬ record ⾥, We from ⽹ Download and install various third-party modules ⼀ Put it all here ⽬ record .

1.10 The first 3⽅ Party open source module installation

How to download code from this platform ?

  1. Directly on ⾯ Face this ⻚ page ⾯ On the surface download, After downloading , Unzip and enter ⼊ Enter into ⽬ Catalog , Of board ⾏ Run the following command to complete the installation
 Compile source code
python setup.py build Installation source
python setup.py install
  1. Directly through pip install
pip3 install paramiko #paramiko Module name 
# pip Orders will ⾃ Automatically download the module package and complete the installation .

Software ⼀ In general, they will be ⾃ Automatically install you python install ⽬ This of the directory ⼦ Son ⽬ Catalog ⾥ Li Li

/your_python_install_path/3.6/lib/python3.6/site-packages

pip The command will be connected to foreign by default python Officer, ⽅ Side server download , Speed ⽐ It's slow , You can also make ⽤ Use domestic ⾖ Douban source , data Will regularly synchronize with foreign officials ⽹ network , Much faster .

 pip install -i http://pypi.douban.com/simple/ alex_sayhi --trusted-host pypi.douban.com #alex_sayhi Module name 
  • -i after ⾯ With ⾖ Source address ;
  • —trusted-host We have to add , Through the website https Security verification ⽤ Of .

1.11 What is a bag (package)

If you write items ⽬ More complicated , There is a lot of code ⽂ Pieces of words , For convenience of management , Sure ⽤ Package management . ⼀ A bag is actually ⼀ individual ⽂ Pieces of ⽬ record , You can put the codes belonging to the same business line ⽂ Pieces are put in the same bag ⾥.

How to create ⼀ A bag ?

Just under the directory establish ⼀ An empty one __init__.py ⽂ Pieces of , This directory becomes a package . This ⽂ This is called package initialization ⽂ Pieces of , It is generally empty , Of course, you can also write something , When you tune ⽤ Under this package and any ⼦ Any module of the package , This __init__.py ⽂ Pieces of Will first hold ⾏.

following Yes a、b 2 A package ,a2 yes a Of ⼦ package ,b2 yes b Of ⼦ package .

If in a_module.py modular ⾥ guide ⼊b2_mod.py Words , What do I do ?

a_module.py Of ⽂ The file path is
/Users/alex/Documents/work/PyProjects/py8days_camp/day6/ Courseware /a/a2/a_module.py

Want to import successfully , Just write the following code ( The right way to call

from day6. Courseware .b.b2 import b2_mod

Why from day6 Start ?⽽ Not from py8days_camp or Courseware To start? ?
Because of you. sys.path In the list , The relevant path has been added

['/Users/alex/Documents/work/PyProjects/py8days_camp/day6/ Courseware /a/a2', '/Users/alex/Documents/work/PyProjects/py8days_camp', # <--- This is this. .. 
'/Applications/PyCharm.app/Contents/helpers/pycharm_display',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages',
'/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend']

Manually add sys.path route

You would say , I didn't add this ‘/Users/alex/Documents/work/PyProjects/py8days_camp’ ah , How does it
Mo Jin sys.path Inside ?

The answer is Pycharm Automatically added for you , If you leave pycharm Hold on to ⾏ This a_module.py It's going to be a mistake .


Alexs-MacBook-Pro:a2 alex$ python3 a_module.py Traceback (most recent call last):
File "a_module.py", line 7, in <module> from day6. Courseware .b.b2 import b2_mod
ModuleNotFoundError: No module named 'day6'

No ⽤ Panic , ⾃ Manually added sys.path The path can be .

Manually add sys.path Implementation of path :

import os
import sys
base_dir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.pa th.dirname(os.path.abspath(__file__)))))) # Take the road path /Users/alex/Documents/work/PyProjects/py8days_camp
print(base_dir)
sys.path.append(base_dir) # Add to sys.path⾥ Li Li 
from day6. Courseware .b.b2 import b2_mod

Two 、⼏ A regular ⽤Python modular

2.1 System tune ⽤ use OS modular

os modular It provides many functions that allow your program to interact directly with the operating system .

import os
Get current job ⽬ record , At present Python The script works ⽬ Recording path : os.getcwd()
Returns the specified ⽬ All recorded ⽂ Pieces and ⽬ Record the name :os.listdir()
Function to delete ⼀ File :os.remove()
Delete multiple directories :os.removedirs(r“c:\python”)
Check whether the given path is ⼀ individual ⽂ Pieces of :os.path.isfile()
Check whether the given path is a ⽬ record :os.path.isdir()
Determine whether it is an absolute path :os.path.isabs()
Verify that the given path really exists :os.path.exists()
return ⼀ Path ⽬ Record name and file name :os.path.split() e.g
os.path.split('/home/swaroop/byte/code/poem.txt') result : ('/home/swaroop/byte/code', 'poem.txt')
Detach extension :os.path.splitext() result :('/usr/local/test', '.py')
e.g os.path.splitext('/usr/local/test.py')
Get pathname :os.path.dirname()
Get the absolute path : os.path.abspath()
obtain ⽂ Piece name :os.path.basename()
shipment ⾏shell command : os.system()
Read operating system environment variables HOME Value :os.getenv("HOME")
Returns all environment variables of the operating system : os.environ
Set system environment variables , Only program operation ⾏ It's valid when you walk :os.environ.setdefault('HOME','/home/alex')
Give the current platform to make ⽤ Of ⾏ Terminator :os.linesep Windows Use '\r\n',Linux and MAC Use '\n'
Indicate the platform you are using :os.name about Windows, It is 'nt',⽽ about Linux/Unix⽤ user , It is 'posix'
rename :os.rename(old, new)
Create multiple levels ⽬ record :os.makedirs(r“c:\python\test”)
Create a single ⽬ record :os.mkdir(“test”)
Get file properties :os.stat(file) Modify file permissions and timestamps :os.chmod(file)
get files ⼤ Small :os.path.getsize(filename)
combination ⽬ Directory name and ⽂ file name :os.path.join(dir,filename)
change ⼯ Work ⽬ Directory to dirname: os.chdir(dirname)
Get the current terminal ⼤ Big ⼩ Small : os.get_terminal_size()
Kill process : os.kill(10884,signal.SIGKILL)

2.2 time modular In normal code , We often need to deal with time . stay Python in , Modules related to time processing include :time,datetime, calendar( Rarely used , Don't speak ), Next ⾯ To introduce .

When we write a program, the processing between can be divided into the following 3 Kind of :

  • Display of time , On the screen 、 Record ⽇ Records, etc “2022-03-04” ;
  • Time conversion ,⽐ Such as string format ⽇ The period turns into Python Medium ⽇ The date type ;
  • Operation of time , Calculate the difference between two dates, etc .

stay Python in , There's usually this ⼏ Kind of ⽅ To express time :

  1. Time stamp (timestamp), It means from 1970 Every year 1⽉1⽇00:00:00 Start offset in seconds . Example ⼦ Son : 1554864776.161901;

  2. Formatted time string , such as “2020-10-03 17:54”;

  3. Tuples (struct_time) There are nine elements . because Python Of time The module realizes the main functions ⽤C library , So various platforms may
    Somewhat different ,mac On :time.struct_time(tm_year=2020, tm_mon=4, tm_mday=10, tm_hour=2, tm_min=53, tm_sec=15, tm_wday=2, tm_yday=100, tm_isdst=0)

    time Module's constant ⽤ Method of use

  • time.localtime([secs]) : take ⼀ A timestamp is converted to the current time zone struct_time. if secs Parameter not provided ,
    The current time shall prevail .

  • time.gmtime([secs]) : and localtime()⽅ The method is similar to ,gmtime()⽅ Law is to ⼀ Timestamps are converted to UTC The time zone
    (0 The time zone ) Of struct_time.

  • time.time() : Returns the timestamp of the current time . time.mktime(t) : take ⼀ individual struct_time Convert to timestamps .

  • time.sleep(secs) : The thread delays the specified time ⾏, The unit is in seconds .

  • time.strftime(format[, t]) : hold ⼀ A tuple representing time or struct_time( Such as by time.localtime() and time.gmtime() return ) Convert to formatted time string . If t Not specified , Will pass on ⼊ time.localtime().

give an example : time.strftime(“%Y-%m-%d %X”, time.localtime()) # Output ’2017-10-01
12:14:23’

  • time.strptime(string[, format]) : hold ⼀ A string of formatted time characters is converted into struct_time. Actually it
    and strftime() Inverse operation .

give an example : time.strptime(‘2017-10-3 17:54’,”%Y-%m-%d %H:%M”) # Output time.struct_time(tm_year=2017, tm_mon=10, tm_mday=3, tm_hour=17, tm_min=54, tm_sec=0, tm_wday=1, tm_yday=276, tm_isdst=-1)
String to time format corresponding table

2.3 datetime modular

phase ⽐ On time modular ,datetime Module connection ⼝ It's more intuitive 、 Easier to call datetime The module defines the following ⼏ Classes :

  • datetime.date: Express ⽇ Date class . often ⽤ The properties used are year, month, day;
  • datetime.time: Class representing time . often ⽤ The properties used are hour, minute, second, microsecond;
  • datetime.datetime: Express ⽇ Date time .
  • datetime.timedelta: Indicates the time interval , That is, between two time points ⻓ length .
  • datetime.tzinfo: Information about time zones .( this ⾥ This kind of , Interested children's shoes can refer to python⼿ manual )

What we need to remember ⽅ The method is only as follows ⼏ How many? :

  1. d=datetime.datetime.now() Returns the current datetime⽇ The date type , d.timestamp(),d.today(), d.year,d.timetuple() etc. ⽅ The method can be adjusted ⽤ use
  2. datetime.date.fromtimestamp(322222) hold ⼀ A timestamp is converted to datetime⽇ The date type
  3. Time operations
 >>> datetime.datetime.now()
datetime.datetime(2017, 10, 1, 12, 53, 11, 821218)
>>> datetime.datetime.now() + datetime.timedelta(4) # current time +4 God 
datetime.datetime(2017, 10, 5, 12, 53, 35, 276589)
>>> datetime.datetime.now() + datetime.timedelta(hours=4) # current time +4⼩ Hours 
datetime.datetime(2017, 10, 16, 53, 42, 876275)
  1. Time to replace
 >>> d.replace(year=2999,month=11,day=30)
datetime.date(2999, 11, 30)

2.4 random random number

There are many places in the program ⽅ need ⽤ To random characters ,⽐ Such as login ⽹ Random verification code of the station , adopt random Modules can be easily ⽣ Into a random string .


>>> random.randrange(1,10) # return 1-10 Between ⼀ A random number , Not included 10
>>> random.randint(1,10) # return 1-10 Between ⼀ A random number , Include 10
>>> random.randrange(0, 100, 2) # Random selection 0 To 100 Even number between 
>>> random.random() # return ⼀ A random floating point number 
>>> random.choice('abce3#[email protected]') # return ⼀ Random characters in a given data set '#'
>>> random.sample('abcdefghij',3) # Select a specific number of characters from multiple characters ['a', 'd', 'b']
#⽣ Generate random character strings 
>>> import string
>>> ''.join(random.sample(string.ascii_lowercase + string.digits, 6)) '4fvda1'
# Shuffle 
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(a)
>>> a
[3, 0, 7, 2, 1, 6, 5, 8, 9, 4]

2.5 Sequence serialization json modular What is Json?

JSON(JavaScriptObject Notation, JS Object shorthand ) yes ⼀ A lightweight data exchange format . It takes ⽤ Totally alone ⽴ Based on programming language ⾔ Text format to store and represent data . A simple and clear hierarchy makes JSON Become an ideal data exchange language ⾔. Easy to ⼈ People read and write , It's also easy to machine analyze and ⽣ Generate , And effectively improve ⽹ Network transmission efficiency .

Json Works of ⽤ for this reason ⽤ Used in different languages ⾔ Verbal connection ⼝ Data exchange between ports ,⽐ For example, you put python Of list、dict Just throw it to javascript, It is the solution It's impossible to analyze .2 A word ⾔ No one knows each other .Json It's like computer English , Can help each language ⾔ Implement data types between words Mutual conversion of .

JSON⽀ Supported data types
Python String of characters in 、 Numbers 、 Column list 、 Dictionaries 、 aggregate 、 Boolean type , Can be sequenced into JSON String of characters , By any other programming language ⾔ Word analysis

What is serialization ?
Serialization refers to the memory ⾥ The data type in is changed into character string , So that it can be stored on the hard disk or through ⽹ Network transmission to remote network , Because the hard drive or ⽹ Network transmission can only accept bytes

Why serialize ?
When you play the game , I'm tired , stop , Turn off the game 、 Thought about 2 Play again ,2 After heaven , game ⼜ Since you last stopped ⽌ Continue to transport ⾏, The progress of your last game must be saved on your hard disk , In what form ? During the game ⽣ Many temporary data are irregular , Maybe when you turn off the game, there's 10 Column list ,3 A data set of nested dictionaries is stored in memory ⾥, It needs to be saved ? How do you save ? Turn the list into ⽂ file ⾥ More ⾏ Multi column form ? What about nested dictionaries ? There's no way to save . therefore , If there is a way, you can directly save the memory data to the hard disk , Next time the program starts , And read it back from the hard disk , In the original format , That's great .

⽤ Two modules for serialization
json,⽤ For strings and python Between data types ⾏ transformation pickle,⽤ On python Unique types and python The data types of ⾏ transformation .

pickle

The module provides four functions :dumps、dump、loads、load


import pickle
data = {
'k1':123,'k2':'Hello'}
# pickle.dumps Converting data into bits in a special form is just python language ⾔ Character string of speech recognition 
p_str = pickle.dumps(data) # Be careful dumps It turns the data into bytes Format print(p_str)
# pickle.dump Converting data into bits in a special form is just python language ⾔ Character string of speech recognition , And write ⼊ Enter into ⽂ file with open('result.pk',"wb") as fp:
pickle.dump(data,fp)
# pickle.load from ⽂ file ⾥ Load inside f = open("result.pk","rb") d = pickle.load(f) print(d)

json

Json The module also provides four functions :dumps、dump、loads、load, Usage follows pickle Agreement .


import json
# json.dumps Convert the data into all program languages in a special form ⾔ Character strings recognized by all words 
j_str = json.dumps(data) # Be careful json dumps⽣ What is generated is a string of characters , No, it's not bytes print(j_str)
#dump⼊ Enter into ⽂ file 
with open('result.json','w') as fp:
json.dump(data,fp) # from ⽂ file ⾥ Li Li load
with open("result.json") as f: d = json.load(f)
print(d)

json vs pickle:

JSON:

  • advantage : Cross language ⾔ said ( Different languages ⾔ Data transmission between words can ⽤ use json Handover )、 Volume ⼩ Small
  • shortcoming : Can only ⽀ Support int\str\list\tuple\dict
    Pickle:
  • advantage : Specially designed for python Design ,⽀ Support python All data types
  • shortcoming : Only in python Chinese envoy ⽤ use , Storing data takes up space ⼤ Big

2.6 Excel Processing module The first 3⽅ Open source module , install

pip install openpyxl

2.6.1 open ⽂ file

⼀、 establish


from openpyxl import Workbook # Instantiation 
wb = Workbook()
# Get current active Of sheet
ws = wb.active
print(sheet.title) # Print sheet Table name sheet.title = "salary luffy" # Change sheet name 

⼆、 Open the existing ⽂ Pieces of

 >>> from openpyxl import load_workbook
>>> wb2 = load_workbook('⽂ File name .xlsx')

2.6.2 Writing data


# The way ⼀ One : Data can be assigned directly to cells ( Can lose ⼊ Enter the formula ) sheet["C5"] = "Hello gold ⻆ King "
sheet["C7"] = "Hello ⾦ Gold and gold ⻆ horn ⼤ King 2"
# The way ⼆: Can be attached ⾏, Start with the first column and attach ( From the bottom ⽅ empty ⽩ It's about , From the far left )( You can enter multiple lines ) sheet.append([1, 2, 3])
# Mode three :Python The type will be ⾃ Automatic conversion 
sheet['A3'] = datetime.datetime.now().strftime("%Y-%m-%d")

2.6.3 Selection table


# sheet The name can be used as key Into the ⾏ Row index 
ws3 = wb["New Title"]
ws4 = wb.get_sheet_by_name("New Title")
print(wb.get_sheet_names()) # Print all sheet sheet = wb.worksheets[0] # For the first 1 individual sheet

2.6.4 Save the table

wb.save('⽂ File name .xlsx')

2.6.5 Traverse table data

  • Press ⾏ Traverse

for row in sheet: # Loop to get table data 
for cell in row: # Loop through each cell data 
print(cell.value, end=",")
print()
  • Traverse by column

# A1, A2, A3 In this order 
for column in sheet.columns:
for cell in column:
print(cell.value,end=",")
print()

Traverse the specified ⾏& Column


# From 2⾏ Line by line ⾄ To 5⾏ Line line , Every time ⾏ Print line by line 5 tall and big in stature 
for row in sheet.iter_rows(min_row=2,max_row=5,max_col=5):
for cell in row:
print(cell.value,end=",")
print()

Traverse the specified ⼏ Columns of data
Get the 2- The first 5 Columns of data

for col in sheet.iter_cols(min_col=2,max_col=5,):
for i in col:
print(i.value,end=",")
print()

2.6.6 Delete ⼯ Worksheet


# ⽅ type ⼀ 
wb.remove(sheet)
# The way ⼆
del wb[sheet]

2.6.7 Set cell style

⼀、 Need to guide ⼊ Class

from openpyxl.styles import Font, colors, Alignment

⼆、 typeface
The following code specifies the isoline 24 Number , Bold italics , Typeface ⾊ Red . Direct use ⽤cell Of font attribute , take Font Object is assigned to it .


bold_itatic_24_font = Font(name=' Isoline ', size=24, italic=True, color=colors.RED, bold=True) # Declaration style 
sheet['A1'].font = bold_itatic_24_font # Style cells 

3、 ... and 、 Yes ⻬⽅ type
It is also used directly cell Properties of aligment, this ⾥ Specify vertical centering and ⽔ In the middle . Except center, You can also make ⽤right、left Equal parameter .

 # Set up B1 The data in is vertically centered and ⽔ Horizontal center 
sheet['B1'].alignment = Alignment(horizontal='center', vertical='center')

Four 、 Set up ⾏⾼& Column width


# The first 2 The line is high 
sheet.row_dimensions[2].height = 40
# C Column width 
sheet.column_dimensions['C'].width = 30

2.7 Mail delivery smtplib

SMTP(Simple Mail Transfer Protocol) Simple Mail Transfer Protocol , It is ⼀ Group rules for sending mail from source address to destination address , It controls the transfer of letters ⽅ type .

Python Yes SMTP⽀ hold smtplib and email Two modules , email Responsible for the construction of mail , smtplib Responsible for sending mail , it Yes smtp Agreement advance ⾏ Simple encapsulation .

2.7.1 The simplest way to send a letter is as follows :


import smtplib
from email.mime.text import MIMEText # The mail is ⽂ writing 
from email.header import Header # Email header 
# Log in to the mail server 
smtp_obj = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465) # In the sender's mailbox SMTP The server , End ⼝ The mouth is 25
smtp_obj.login("[email protected]", "xxxx-sd#gf") # The brackets correspond to the sender's email account 、 Mailbox password 
#smtp_obj.set_debuglevel(1) # Display debug information 
# Set header information 
msg = MIMEText("Hello, ⼩ Cute guy , About ?800 On ⻔ door , New to school ⽣ Have a sister ...", "plain", "utf-8") msg["From"] = Header(" Come on ⾃ From Nami's greetings ","utf-8") # sender 
msg["To"] = Header(" Predestined relationship ⼈ people ","utf-8") # The receiver 
msg["Subject"] = Header(" Nami's letter ","utf-8") # The theme 
# send out 
smtp_obj.sendmail("[email protected]", ["[email protected]", "[email protected]"], msg.as_string())

2.7.2 send out HTML Format message
Just change ⼀ Next MIMEText() The first 2 The parameter is html Can


# Set header information mail_body = '''
<h5>hello,⼩ Cute guy </h5>
<p>
⼩ brother , About ?800, New to school ⽣ Sister .. <a href="http://wx1.sinaimg.cn/mw1024/5ff6135fgy1gdnghz2vbsg205k09ob2d.gif"> This is me Photos of ⽚ slice </a></p>
</p> '''
msg = MIMEText(mail_body, "html", "utf-8")

2.7.3 stay HTML⽂ Figures are inserted in this ⽚

 # -*- coding:utf-8 -*-
# created by Alex Li - Road ⻜ Flying school city 
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
# Log in to the mail server 
smtp_obj = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465) # Hair parts ⼈ People in the mailbox SMTP service Apparatus , End ⼝ The mouth is 25
smtp_obj.login("[email protected]", "333dsfsf#$#") # The corresponding in parentheses is the email ⼈ Personal e-mail account Number 、 Mailbox password 
smtp_obj.set_debuglevel(1) # Display debug information 
# Set header information mail_body = '''
<h5>hello,⼩ Cute guy </h5>
<p>
Cute guy , About ?800, New to school ⽣ Sister .. <p><img src="cid:image1"></p>
</p> '''
msg_root = MIMEMultipart('related') # Allow adding attachments 、 chart ⽚ Film, etc 
msg_root["From"] = Header(" Come on ⾃ From Nami's greetings ","utf-8") # sender 
msg_root["To"] = Header(" Predestined relationship ⼈ people ","utf-8") # The receiver 
msg_root["Subject"] = Header(" Nami's letter ","utf-8") # The theme 
# Allow to add diagram ⽚
msgAlternative = MIMEMultipart('alternative') msgAlternative.attach(MIMEText(mail_body, 'html', 'utf-8'))
msg_root.attach(msgAlternative) # Put the mail straight ⽂ Add text content to msg_root⾥ Li Li 
# Loading diagram ⽚,
fp = open('girl.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Definition chart ⽚ slice ID, stay HTML ⽂ Quote... In the text ⽤ 
msgImage.add_header('Content-ID', '<image1>')
msg_root.attach(msgImage) # Add diagram ⽚ Slice to msg_root object ⾥ Li Li 
# send out 
smtp_obj.sendmail("[email protected]", ["[email protected]", "[email protected]"], msg_root.as_string())

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved