Python3 Study notes (2)

Source: Internet
Author: User

I. Object-oriented (initial knowledge)
Consists of classes and methods, which encapsulate a lot of functionality, and according to this class, you can create an object of this class, that is, the object is created from this class, and the object is to be found in this class when it uses a function.
Cases:
Str
-Function One
-Function Two
-Function Three
-。。。

S1 = ' Alex '
STR is a class, and S1 is an object created from this class.

Second, set set
Set is an unordered, non-repeating, nested collection.

1, syntax: SE = {} or SE = set () or SE = set ((11,22,33,33)), set () is actually called the __init__ method inside this class
The notation is similar to a dictionary, but the dictionary is represented by a key and a value, and a content in set represents an element.
Example 1
Se = {' 123 ', ' 345 '}

2. Adding elements
Cases
s = Set ()
S.add (123)
Print (s)
Add the same element repeatedly, printing only one

3. Clear the elements in the collection
Cases
S.clear ()
Print (s)

4. Copy
Cases
S1 = s1.copy (s)
Copy belongs to a shallow copy, deepcopy belongs to deep copy

5. Difference value
Cases
S1 = {11,22,33}
S2 = {22,33,44}
S3 = s1.difference (S2)
Print (S3)
The element that exists in the S1 but does not exist in the S2 is placed in the S3

6. Symmetrical difference value
Cases
S1 = {11,22,33}
S2 = {22,33,44}
S3 = s1.symmetric_difference (S2)
Print (S3)
Put the element that exists in the S1 but not in the S2 into S3, and will exist in S2, but the element that does not exist in S1 is put into S3

7, the Difference value update
Cases
S1 = {11,22,33}
S2 = {22,33,44}
S1.difference_update (S2)
The elements that are present in the S1 but do not exist in S2 are updated S1

8, the symmetry difference value update
Cases
S1 = {11,22,33}
S2 = {22,33,44}
S1.symmetric_difference_update (S2)
Print (S3)
Updates the element that exists in S1, but does not exist in S2 to S1, and the element that is present in the S2, but does not exist in S1, is updated into S1

9, remove the specified element (element does not exist, no error)
Cases
S1 = {11,22,33}
S1.discard (11)
Print (S1)
If the removed element does not exist, no error is found

10, remove the specified element (the element does not exist, the error)
Cases
S1 = {11,22,33}
S1.remove (11)
Print (S1)

11. Remove element (randomly remove an element and return the removed element)
Cases
S1 = {11,22,33}
ret = S1.pop ()
Print (S1)
Print (ret)

12, take the intersection
Cases
S1 = {11,22,33}
S2 = {22,33,44}
S3 = s1.intersection (S2)
Print (S3)
Assign the elements of both S1 and S2 to S3

13, take the intersection update
Cases
S1 = {11,22,33}
S2 = {22,33,44}
S1.intersection_update (S2)
Print (S1)
Update the elements of S1 and S2 to S1

14. Determine if there is a intersection
Cases
S1 = {11,22,33}
S2 = {22,33,44}
p = s1.isdisjoint (s2)
Determines whether two sets have an intersection, returns true if none, and returns false

15, and set
Cases
S1 = {11,22,33}
S2 = {22,33,44}
S3 = s1.union (S2)
Print (S3)
Merge elements of S1 and S2 into S3

16. Update
Cases
S1 = {11,22,33}
Li = [1,2,3,4]
S1.update (LI)
Bulk add multiple elements into s1,update to accept data that can be used for loops
Note that the string is also a recyclable data

Practice:
Old_dict = {
"#1": 8,
"#2": 4,
"#4": 2
}

New_dict = {
"#1": 4,
"#2": 4,
"#3": 2
}

These two dictionaries are available to meet the following requirements:
1. Which slots should be removed
2, you should increase the number of slots
3, should update those slots

Third, the function of the first knowledge
Process-oriented programming: from top to bottom 1.1 of the write, encountered repeated operations, generally copied before the operation to paste, resulting in poor code readability, poor code reuse, increase the amount of code.
Functional programming: Functions that will be reused, defined as a function that can be called when used
Grammar:
Def f1 (): #使用def关键字创建一个函数, the function name is F1, the interpreter creates a function in memory for this function to open up a space, add the function body into memory, and create a name for the function, but not straight line function body, the function body when the call is straight line.
Pass #函数中所进行的操作
Note that the function also needs to define the return value to tell the function caller whether the function is straight-line successful.
F1 () #调用函数

Example 1: Sending a message function
Def send_mail ():
Try
Import Smtplib
From Email.mime.text import Mimetext
From email.utils import formataddr

msg = mimetext (' message content ', ' plain ', ' utf-8 ')
Msg[' from '] = FORMATADDR (["Guijiang", ' [email protected] ')
msg[' to ' = Formataddr (["Guijiang", ' [email protected] ')
msg[' Subject ' = "Subject"

Server = Smtplib. SMTP ("smtp.189.cn", 25)
Server.login ("[Email protected]", "198787")
Server.sendmail (' [email protected] ', [' [email protected] ',], msg.as_string ())
Server.quit ()
Except
#发送失败执行
Return False
Else
#发送成功执行
Return True

ret = Send_mail () #ret用来接受函数的返回值
IF RET:
Print (' Send success ')
Else
Print (' Send failed ')
Note: try, except, else is used to receive the exception, and execution of the related statement, try to run the function body above, if an exception occurs, run the code under except, otherwise run the code under else.

Example 2
Def f1 ():
Print (' 123 ')
Return ' 111 '
Print (' 456 ')
F1 ()
Note, in the function, after executing the return statement, immediately stop executing the function, that is, the statement after return will never be executed.

Example 3
Def f1 ():
Print (' 123 ')
F1 ()
Note: If no return value is defined in the function, the default return is None

1. Function parameters
def send_mail (Xxoo):
Try
Import Smtplib
From Email.mime.text import Mimetext
From email.utils import formataddr

msg = mimetext (' message content ', ' plain ', ' utf-8 ')
Msg[' from '] = FORMATADDR (["Guijiang", ' [email protected] ')
msg[' to ' = Formataddr (["Guijiang", ' [email protected] ')
msg[' Subject ' = "Subject"

Server = Smtplib. SMTP ("smtp.189.cn", 25)
Server.login ("[Email protected]", "198787")
Server.sendmail (' [email protected] ', [Xxoo,], msg.as_string ())
Server.quit ()
Except
#发送失败执行
Return False
Else
#发送成功执行
Return True

ret = Send_mail () #ret用来接受函数的返回值
IF RET:
Print (' Send success ')
Else
Print (' Send failed ')

ret = SendMail (' [email protected] ')
Note: Xxoo is a formal parameter, when the function is called, the actual arguments are passed in the parentheses, and the function body is equivalent to the Xxoo as a variable, the actual parameters are assigned to Xxoo, which is used by the function body.

Example 1
While True:
EM = input (' Please enter email address: ')
result = Send_mail (EM)
if result = = True:
Print (' Send success ')
Else
Print (' Send failed ')

Example 2
def send_mail (xxoo,content):
Print (' Send success: ', xxoo,content)
Send_mail (' [email protected] ', ' SB ')
Note: The formal parameters can be multiple, in the passing of the parameters also need to pass the corresponding number of actual parameters.

2. Default parameters
Example 1
def send_mail (xxoo,content,xx= ' OK '):
Print (' Send success: ', xxoo,content,xx)
Send_mail (' [email protected] ', ' SB ')
Note: If the formal parameter xx set the default value, then in the parameter, if not passed in with the XX position corresponding to the actual parameters, XX use OK as the actual parameter, if the actual parameters for XX passed, then use the value passed in as XX value. Python specifies that if a default parameter is specified for a formal parameter, the formal parameter must be placed at the end of all formal parameters.

3. Specify parameters
Example 1
def send_mail (xxoo,content):
Print (' Send success: ', xxoo,content)
Send_mail (content= ' [email protected] ', xxoo= ' SB ')
Note: The formal parameters corresponding to the actual parameters can be specified at the time of invocation, in which case the actual parameter passed in does not need to correspond to the position one by one of the formal parameter.

4. Dynamic Parameters
Example 1
def f1 (*args):
Print (args)
F1 (11,22, ' Alex ', ' HHHH ')
Note: You can use * to represent a number of parameters, so that a formal parameter can accept a number of actual parameters, in the function body, this passed in a number of actual parameters will form a tuple assigned to this form parameter.

Example 2
def f1 (*args):
Print (args)
Li = [11,22,33,44]
F1 (LI)
Note: If the actual parameter passed in is a list, then inside the function body, only the list is assigned as an element in the tuple to the formal parameter.

Example 3
def f1 (*args):
Print (args)
Li = [11,22,33,44]
F1 (*li)
Note: If the actual parameter passed in also has an * number, it means that each element in the list is converted to each element of a tuple, and the string is the same

Example 4
def f1 (**args):
Print (args)
F1 (n1= ' li ')
Note: When the formal parameter has two *, the actual parameters passed in will become the elements in the dictionary, depending on the characteristics of the dictionary, you need to have key and value, so you need to pass in the specified parameters when passing the actual parameters

Example 5
def f1 (**args):
Print (args)
DiC = {' K1 ': ' v1 ', ' K2 ': ' V2 '}
F1 (**dic)
Note: If you also use two * when passing in the actual parameters, it means that the parameters are formed into a single dictionary instead of the elements in the dictionary.

Example 6: Universal parameters
def f1 (*args,**kwargs):
Print (Args,kwargs)
F1 (11,22,33,44,k1= ' v1 ', k2= ' v2 ')
Note: In the case where the formal parameter is both * and * *, if the actual parameter passed in has both a list and a specified argument, the list is automatically placed in the * list, and the specified parameters are placed in the dictionary. * The form parameters must precede the formal parameters of the * *, the order cannot be changed.

5. Format ()
The format () function is used for formatting output.
Example 1
s = ' I am {0},age {1} '. Format (' Alex ', 18)

Example 2
s = ' I am {0},age {1} '. Format (*[' Alex ', 18])

Example 3
s = ' I am {name},age {age} '. Format (name= ' Alex ', age=18)

Example 4
s = ' I am {name},age {age} '. Format (**{name: ' Alex ', age:18})

6. Supplementary knowledge
Example 1
def f1 (A1,A2):
Return A1 + A2

def f1 (A1,A2):
Return A1 * A2

ret = F1 (8,8)
Print (ret)
Note: In the above example, because Python is executed from top to bottom, when two F1 functions are present, the last defined function takes effect, and the memory created by the first defined function is purged periodically by the garbage collection mechanism.

Example 2
Def f1 (A1):
A1.append (999)

Li = [11,22,33,44]
F1 (LI)
Print (LI)
Note: Python passes a reference to memory when passing parameters, so the result of this is [11,22,33,44,999]

Example 3, local variables
Def f1 ():
name = ' Alex '
Print (name)
def f2 ():
Print (name)
Note: A variable defined in a function can only be used in the body of the function, and its scope is the body of the function.

Example 4, global variables
name = ' Alex '
Def f1 ():
Age = 18
Print (Age,name)
def f2 ():
Age = 19
Print (Age,name)
Note: Because the variable name is defined in the file, it is scoped to the entire py file, and all scopes are readable.
Note: When defining a global variable, the variable name is capitalized, which is a unspoken rule that is easy for code to read.

Example 5
name = ' Alex '
Def f1 ():
Age = 18
Name = ' 123 '
Print (Age,name)
Note: If a local variable with the same name as the global variable appears in the function body, the local variable is executed preferentially when the function executes. That is, local variables are first used with global variables.

Example 6
name = ' Alex '
Def f1 ():
Age = 18
Global Name
Name = ' 123 '
Print (Age,name)
Note: If you need to modify a global variable in the function body, you need to use the global variable name before modifying it to declare that the variable is a global variable before it can be modified.

Example 7
name = [11,22,33]
Def f1 ():
Age = 18
Name.append (' 44 ')
Print (Age,name)
Note: If a global variable is a list, a dictionary, a list element within a tuple, a collection, it can be modified directly in the body of the function, but it cannot be re-assigned.

7, the function of the unspoken rules
Need to add notes to explain their role
Two empty lines between functions and functions

Four or three-dollar operation (Trinocular operation)
Syntax: name = ' Alex ' if 1 = = 1 Else ' SB '
Equivalent to
If 1 = = 1:
name = ' Alex '
Else
name = ' SB '
Note: The ternary operation is actually shorthand for a simple if else statement.

V. Lambda expression
Syntax: F2 = lambda a1:a1 + 100
Equivalent to
def f2 (A1):
Return A1 + 100
Note: You can use lambda expressions to implement some simple functions.

Six, built-in functions
1. ABS ()
A function that takes an absolute value
Cases
n = ABS (-1)

2. All ()
Receives an object that can be iterated, such as a list, if the elements in this object are all true, returns True if an element is false and returns false
On behalf of False:0,none, "", [], ()

3. Any ()
To receive an object that can be iterated, such as a list, if the element in this object has a true time return true, all elements are false when the return false

4. ASCII ()
__repr__ method for automating object execution
Cases
Class Foo:
def __repr__ (self):
Return "333"

n = ASCII (Foo ())
Print (n)

5. Bin ()
Accept a decimal, and convert this decimal to binary return, the return value format is 0b+ binary value

6. Oct ()
Accept a decimal, and convert this decimal to octal return, the return value format is 0o+ octal value

7, Hex ()
Accept a decimal and convert this decimal to hexadecimal return, return value formatted as 0x+ hexadecimal value

8, BOOL ()
Accepts a value and returns the Boolean value represented by this value, which is true or false
On behalf of False:0,none, "", [], ()
On behalf of Ture:1,-1, "", [], ()

9. Important: Bytes ()
One byte is 8 bits
A UTF-8 encoded Kanji account of 3 bytes
A GBK encoded Kanji account of 2 bytes
The function of bytes () is to convert a Chinese character to a byte, which returns a byte in 16 binary form.
Example 1
s = "Li Jie"
n = bytes (s,encoding= "Utf-8")
Print (n)

Example 2
s = "Li Jie"
n = bytes (s,encoding= "GBK")
Print (n)

10, ByteArray ()
The principle is the same as bytes (), but bytes () returns a string of multiple bytes, and this function returns a list of each byte as an element.

11. STR ()
This function converts a character converted into a byte into a string, noting the need to provide an encoding parameter
Cases
s = "Li Jie"
n = bytes (s,encoding= "Utf-8")
A = str (n,encoding= "Utf-8")
Print (a)

Vii. file operation, open () function
1. Open File Opening method
Example 1
f = open ("DB", "R")
Open file with read-only mode

Example 2
f = open ("DB", "W")
File open only, note: All contents of the file will be emptied when opened

Example 3
f = open ("DB", "X")
If an error occurs when the DB file is present, create the file if it does not exist and open the file in W mode, this is Python3. X is added.

Example 4
f = open ("db", "a")
F.write ("Li Jie")
F.close
Append to the file, you can append content after the original content of the file.

Note: You need to set the encoding according to the way the file is saved, and generally save it in Utf-8. The string is read, so it needs to be a string at the time of writing.

Example 5
f = open ("DB", "AB")
F.write (Btyes ("Li Jie", encoding= "Utf-8"))
F.close
Note: Adding B to the open mode means that the byte type is read directly, so it is necessary to write a byte type, that is, binary.

Example 6
f = open ("db", "r+", encoding= "Utf-8")
data = F.read ()
F.seek (1)
F.write ("777")
F.close
Note: Use r+ to open the file in a readable, writable way (more), in Python, as long as there is a read operation, the pointer will be put to the end, when adding content by default added to the last, if you need to modify the pointer position, you can use the Seek method to adjust, but the added content will overwrite the character after the pointer position But seek is always positioned according to the position of the byte, so it is possible to break the kanji because a Chinese character is 3 or 2 bytes

Example 7
f = open ("db", "r+", encoding= "Utf-8")
data = F.read (1)
Print (F.tell ())
F.write ("777")
F.close
Note: F.tell () Displays the position of the pointer after it has been read (always in bytes).

Example 8
f = open ("db", "w+", encoding= "Utf-8")
Note: When you open a file using w+, all the contents of the file are purged before the content is read.

Example 9
f = open ("db", "A +", encoding= "Utf-8")
Note: When you open a file with a +, the characters you add are always added last.

2. Operation files
Example 1
f = open ("db", "r+", encoding= "Utf-8")
F.read ()
Note: If no parameter reads all content, read by byte if B is open, otherwise read by character

Example 2
F.tell ()
Note: Gets the current pointer position

Example 3
F.seek ()
Note: Specify the pointer position, always follow the byte operation

Example 4
F.write ()
Note: Write the data, if there is b write the byte, otherwise write the character

Example 5
F.close ()
Note: Close file

Example 6
F.fileno ()
Note: Returns a file descriptor

Example 7
F.flush ()
Note: Force the write content to be brushed into the hard disk

Example 8
F.readable ()
Note: Detects if the file is readable

Example 9
F.seekable ()
Note: Detects if the pointer is operable

Example 10
F.readline ()
Note: Only one row is read, and after reading the pointer is at the end of the line, if read again, it will be read to the following row

Example 11
F.write ()
Note: Detects if the file is writable

Example 12
F.truncate ()
Note: Empty the contents of the pointer where it is located

Example 13 (Common)
f = open ("db", "r+", encoding= "Utf-8")
For line in F:
Print (line)
Note: Use a For loop to loop through each line of file content and output

Example 14
F.readlines ()
Note: Read all the lines of a file, form a list, and each row of data is an element in the list

3. Close the file
Example 1
F.close ()
Note: Close file

Example 2
With open ("db") as F:
Pass
Note: Use with to open a file and automatically close the file after the internal code block has finished executing.

Example 3
With open ("DB1", "R", encoding= "Utf-8") as F1,open ("DB2", "W", encoding= "Utf-8") as F2:
Times=0
For line in F1:
Time + = 1
If times <=10:
F2.write (line)
Else
Break
Note: Use with to open more than one file at a time, and then close when you are done. Usage Scenario: Writes some content of DB1 to DB2.

Example 4
With open ("DB1", "R", encoding= "Utf-8") as F1,open ("DB2", "W", encoding= "Utf-8") as F2:
For line in F1:
New_str = Line.replace ("Alex", "St")
F2.write (NEW_STR)
Note: Read each line in F1, and then replace "Alex" and write F2.

Homework:
See more: http://www.cnblogs.com/wupeiqi/articles/4950799.html



Python3 Study notes (2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.