Introduction to Python
This is the fourth day of my participation in Gwen Challenge
1.1 Python features
- Python is an object-oriented language in which everything is an object
- Python is an interpreted language
- Python is an interactive language, meaning that it does command programming in terminals
- Python is a cross-platform language. You can run Python on any operating system.
- Python has a powerful and rich library, also known as the glue language, that makes it easy to combine modules written in other languages (mainly C/ C ++)
1.2 Advantages and disadvantages of Python
- Advantages:
- Easy to maintain and learn
- Extensive standard library [provides a large number of tools]
- Strong scalability
- Python has interfaces for most databases (Mysql, sqliters3, MongoDB, Redis, etc.)
- Support GUI programming [graphical interface]
- Disadvantages:
- Python code runs slowly compared to C
- Code cannot be encrypted
1.3 Python Code execution process
Process: compile the source code into bytecode (.pyc) --> Python Virtual machine --> execute the compiled bytecode --> Python virtual machine translates the bytecode into the corresponding machine instructions (machine code). When a Python program is running, bytecode is compiled and stored in memory. When the program is finished, the Python interpreter writes the bytecode objects in memory to a. Pyc file. On the second attempt, first look for the. Pyc file on the hard disk, if found, load directly, otherwise repeat the above process. Advantages: No repeated compilation, improve execution efficiencyCopy the code
Basic syntax in Python
2.1 Memory storage of variables in Python
2.1.1 References and Objects
-
Object: When a data object is created, the value of the object is stored in memory, which is the object itself
-
References: Objects are stored in memory, and outsiders need to manipulate them with references if they want to use their values. The number of references to an object is kept in memory, and when a reference to an object is zero, the object is reclaimed.
2.1.2 Mutable and immutable data types
-
Mutable data type
Mutable data types: Allows to change the value of a variable, for variable to the value of the process, just change the value of a variable, rather than create a new object, so the variable data types of meaning to operation, a variable whose value is variable, the value of the change will not cause a new object, the address will not change, only address or change the content of the expansion.Copy the code
-
Immutable data types
The value of the object itself is immutable. If the value of the variable is changed, it is equivalent to creating a new object. For objects with the same value, there is only one object in memoryCopy the code
Mutable data objects: Lists, dict
Immutable data objects: integer (int), float, string (STR), tuple
Note: Variable and immutable here refer to whether the value of an object in memory can be changed. For immutable objects, a new area in memory must be opened up when the object is operated. For mutable objects, the operation on the object does not apply for a new address, but continues to apply for the address of the object.
2.1.3 Reference Passing and Value Passing (Function Passing Value)
Note: Mutable objects are passed by reference, immutable objects are passed by value.
-
Reference-passing: When passing a list or dictionary, changing the value of a reference modifies the original object
def check(a) : # because lists are mutable objects print(a) print(id(a)) a.append([1.2.3]) return a a = [3.4.5] print(check(a)) print(id(a)) "" "[3, 4, 5] 44909288 [3, 4, 5, [1, 2, 3]] 44909288 "" " Copy the code
-
Value passing: When passing immutable objects, if you change the value of a reference variable, you just create a different object, and the original object does not change
def check1(a) : # Since strings are immutable objects, the address is recreated print(a) print(id(a)) a = "i am test" print(id(a)) return a a = "This is aa" print(check1(a)) print(id(a)) """ This is aa 58547040 58547120 i am test 58547040 """ Copy the code
2.1.4 Deep and Shallow copies
-
Shallow copy: Syntax: copy.copy(). A shallow copy creates a copy of the same type as the original object, but its contents are references to the elements of the original object.
1. Shallow copy replication is a memory reference for mutable, immutable data types
Shallow copies only copy the first layer, and any further data changes will affect the rest.
a = [9.8[1.2].6] A shallow copy is a copy of the parent object reference, both a and B will change the address b = a.copy() b = a[:] # also means shallow copy print(a, b) a.append(2) b.append(3) print("The first layer:", a, b) # Nothing has changed a[2].append(3) b[2].append(4) print("Second layer:", a, b) # Change "" "[9, 8, [1, 2], 6] [9, 8, [1, 2], 6] [9, 8, [1, 2], 6, 2], [9, 8, [1, 2], 6, 3] [9, 8, [1, 2, 3, 4], 6, 2] [9, 8, [1, 2, 3, 4] "" Copy the code
-
Deepcopy: syntax: copy.deepcopy(), to recreate a copy of all data in memory.
1. For mutable data types, deep copy also reinvents nested content
2. For immutable data types, deep-copy references to the same copied memory
"" deep" copy is to create a space in the memory, no matter how complex data structure, as long as the data change, is to open up a piece of memory space to copy down, until the last layer, popular point is, deep copy is to define a variable, in before didn't have anything to do, so change the content of the inside, It's not going to change. "" " import copy a = {1: [1.2.3]} Deep copy will create a new memory space c = copy.deepcopy(a) print(a, c) a[1].append(4) c[1].append(5) print(a, c) "" "{1: [1, 2, 3]} {1: [1, 2, 3]} {1: [1, 2, 3, 4]} {1: [1, 2, 3, 5]} "" " Copy the code
The nature of variables: To create a space in memory in which data of a specified type is stored (entities (objects) are stored in the heap and variables (references) are stored in stack space)
2.2 Basic Data types
Common data types in Python are: Int, float, string, None, True/False, complex, class, function, List, Tuple, set, Dictionary
- ** Immutable data (3) : **Number (Number), String (String), Tuple (Tuple);
- ** Mutable data (3) : **List (Dictionary), Set (Set).
The Python naming convention for constants uses all uppercase variable names. (STATIC=”A”)
Variables in Python do not need to be declared; each variable must be assigned a value before it can be used, and then the variable can be created. (a = b = c = 1, A, b, c = 1, 2, “A”)
2.2.1 Python Data type Conversion
function | describe |
---|---|
chr(x) | Converts an integer to a character |
int(x) | Convert x to an integer |
ord(x) | Converts a character to the corresponding ACSII code |
. | . |
2.3 Keywords, identifiers, and built-in functions
2.3.1 keyword
Keyword: English words that have been given a special meaning in Python
Keywords in Python are viewed using the keyword module
import keyword
print(keyword.kwlist)
"""
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
"""
Copy the code
2.3.2 Naming rules for identifiers
Naming rules for identifiers are as follows: Identifiers can be named using numbers, letters, and underscores (_), but cannot start with a number. Identifiers are case sensitive
Naming conventions:
All words are in lower case, different words are separated by underscores, and the general use of camel nomenclature (small and large hump)
2.3.3 Built-in functions
import sysprint(dir(sys.modules))
Copy the code
Built-in function table;
Built-in function | ||||
---|---|---|---|---|
abs() | dict() | help() | min() | setattr() |
all() | dir() | hex() | next() | slice() |
any() | divmod() | id() | object() | sorted() |
ascii() | enumerate() | input() | oct() | staticmethod() |
bin() | eval() | int() | open() | str() |
bool() | exec() | isinstance() | ord() | sum() |
bytearray() | filter() | issubclass() | pow() | super() |
bytes() | float() | iter() | print() | tuple() |
callable() | format() | len() | property() | type() |
chr() | frozenset() | list() | range() | vars() |
classmethod() | getattr() | locals() | repr() | zip() |
compile() | globals() | map() | reversed() | import(a) |
complex() | hasattr() | max() | round() | |
delattr() | hash() | memoryview() | set() |
2.4 Python operators
2.4.1 Arithmetic and assignment operators
Arithmetic operators:
** exponentiation
// Divisible or floor division
% mod operation
Precedence of common arithmetic operators: ** -> * -> // / % -> + –
Assignment operator:
The assignment operator: =
Compound operators: += -= *= /=
==! = > = < =
2.4.2 Logical Operation
() => not => and => OR
The operator | Logical expression | describe |
---|---|---|
and | x and y | Boolean “and” x,y are True, return True |
or | x or y | Boolean “or” x,y either True, return True |
not | not x | Boolean “not” – returns False if x is True. If x is False, it returns True. |
operator | describe |
---|---|
& | Bitwise and operator: Two values involved in the operation, the result of which is 1 if both corresponding bits are 1, and 0 otherwise |
| | Bitwise or operator: if either of the two corresponding binary digits is 1, the result bit is 1. |
^ | Bitwise xor operator: When two corresponding binary bits differ, the result is 1 |
~ | Bitwise invert operator: Invert each binary bit of data, that is, changing 1 to 0 and 0 to 1. ~x is similar to -x-1. (Operation principle: calculate complement, invert by bit, convert to original code, add 1 at the end) |
<< | Left shift operator: the binary of the operand moves several bits to the left. The number to the right of “<<” specifies the number of bits to move. The high digit is discarded and the low digit is filled with 0. |
>> | Right shift operator: Moves all the binary digits of the operand to the left of “>>” several right, and the number to the right of “>>” specifies the number of digits to move |
0 means False and 1 means True
2.4.3 Membership and identity calculation
Member operator: in not in
Identity operator: is is not(yes, or no)
2.5 Statements in Python
2.5.1 if statement
The two structures of an if statement in Python are:
# 1 if conditional expression: code block # 2 if conditional expression: code block elif conditional expression: code block # 3 if conditional expression: code block else: code blockCopy the code
2.5.2 for statement
While conditional expression: code blockCopy the code
# 9 times 9 times table
line = 0
while line < 10:
temp = 1
while temp <= line:
print(temp, "*", line, "=", temp * line, end="")
temp += 1
print("")
line += 1
1 * 1 = 1 1 * 2 = 2 2 * 2 = 4 1 * 3 = 3 2 * 3 = 6 3 * 3 = 9 1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16 1 * 5 = 5 2 * 2 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36 1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49 1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 7 * 8 = 56 8 * 8 = 64 1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = "81" "
Copy the code
Break breaks the current loop directly
Continue Terminates the current loop and continues the next loop
Python built-in data structures
The most basic data structure in Python is a sequence. Python contains six built-in sequences, including lists, tuples, strings, Unicode strings, buffer objects, and Xrange objects
3.1 String (STR)
3.1.1 Creating a String
Place text between single, double, and triple quotation marks
str1 = ' hello, fanison 'Str1 = "Hello, Fanison" str1 ="""hello word"""
Copy the code
3.1.2 Escaping strings
Native strings: use r
str1 = r"hello, fanison"
Copy the code
3.1.3 String slicing operations
Regardless of the end
-
The index operator s[I] returns the element I of a sequence
-
The slice operator s[I :j] returns an element from the ith element to j-1 in the string
-
The extended slice operator s[I :j:step] takes the element from the ith to the j-1 element in the string with the step size of step, where step is positive and I < I or s[I,-1] is taken backwards
Len of s, the number of elements in s
Min (s) The minimum value of s
Max (s) The maximum value of S
a = [1.2.3.4.5.6.7.8]
print(a[2:)# the subscript starts at 0
print(a[2:5])
print(a[2:7:2])
print(a[2: -1])
print(a[::-1]) # reverse list
print(a[-1: : -1]) # reverse list
"" "[3, 4, 5, 6, 7, 8] [3, 4, 5], [3, 5, 7], [3, 4, 5, 6, 7] [8, 7, 6, 5, 4, 3, 2, 1] "" "
Copy the code
3.1.4 Methods related to strings
S.index (sub [,start [,end]]) find the first occurrence of string sub
STR (STR,beg=0,end=len(string)
S.upper () converts a string to uppercase
S.power () converts a string to lowercase
S. sin (t) joins the string s.trip () in the sequence t with s as delimiter and returns (lstrip, rstrip) after removing undisplayed symbols on both sides of s
S.split (t) gets the list of sectioned s with the character t
S.encode () gets the specified encoded bytes value of s
Bytes.decode () gets the corresponding encoded string of bytes, using the decode function in Python2
S. Enders with(suffix,beg=0, end=len(string)) Checks whether the suffix string ends
x = "do you fuck me?"
print(x.index("y")) Error if not found
print(x.find("z")) If not found, return -1
print(x.upper())
print(x.lower())
print(x.join("-x"))
print(x.split(""))
print(x.encode())
print(x.endswith("f")) # Determine if it ends with an F
""" 3 -1 DO YOU FUCK ME? do you fuck me? -do you fuck me? x ['do', 'you', 'fuck', 'me?'] b'do you fuck me? ' False """
Copy the code
3.2 list (list)
Variables: A window can store only one data at a time
Function: it is equivalent to a window that can store multiple data at the same time
Nature: an ordered collective [order: data is stored in the same order as the underlying storage]
Lists: Allow duplicate elements and allow different types of data to be stored
list1 = [45.23.2.54.54.6."hello".4637.False]list2 = [1.2.3]
Copy the code
check
Access to list elements: starts at 0
- Subscript, index
- slice
- judge
- Len: length Max (): maximum value min(): minimum value index() : subscript
Access by index
print(list1[0])
print(list1[-1])
# print(list1[1000]) list subscript out of bounds
[start: end: step
print(list3[2:)Get the element from the beginning to the specified subscript...
print(list3[2:6]) # intercept the specified interval
print(list3[4:100]) Print (list3[4:]) print(list3[4:])
print(list3[1:6:2]) Special case 2: Step is 1 by default
print(list3[-1: -6]) # if start and end are both negative and step is positive, get []
If start, end, and step are all negative, the list is in reverse order
print(list3[-1: : -1])
print(list3[::-1])
print(list3[-1: -6: -2])
print(2 in list2) # Check whether an element is in the list,true,false
print(2 not in list2)
# 3.1len() to get the list length
print(len(list1))
# 3.2 Max () to get the maximum value in the list
print(max(list1))
# 3.3min(), get the minimum value in the list
print(min(list1))
# 3.4index() gets the index of the first match of the specified element in the original list
print(list1.index(11)) # 11 Index of the list in list1
Copy the code
change
Replacement/modification of list elements
- Through the subscript
list1[0] = 99
print(list1)
print(list1 + list2) Generate a new list
print(list2 * 3) # Repetition of list elements
Copy the code
increase
Add elements
- Append: append, to add an element to the end of a list
- Extend: extends to add elements at the end of the list
- Insert: Inserts at the specified position
l1 = [22.33.44.55]
Add an element to the end of a list
l1.append(66) Append a single element
TypeError: Append () takes exactly one argument (2 given) TypeError: append() takes exactly one argument (2 given)
l1.append([77.88]) # append multiple elements, cannot append directly, through the form of list append, forming a two-dimensional list
# 1.2extend, extends, adds elements at the end of the list
l2 = [22.33.44.55]
Extend (66) #T ypeError: 'int' object is not iterable
l2.extend([66]) # append a single element, not directly. Parameters must be iterable
l2.extend([77.88])
Insert an element at the specified index, with subsequent elements deferred
Insert (index, element to be inserted)
l3 = [22.33.44.55]
l3.insert(2.66) Insert a single element
l3.insert(1[77.88]) Insert multiple elements: Similar to append, insert the entire list directly
Summary: list name. Append can add a single element directly, while extend cannot add multiple elements in a list, while extend only adds elements. Insert (): inserts elements at specified locations"" "Copy the code
delete
Remove elements
- pop()
- remove()
- clear
Remove and retrieve the list element at the specified index on the stack.
list1 = [11.22.33.44.55]
# 1.pop() Note: pop removes the last element by default
result1 = list1.pop()
print(list1)
print(result1) # Delete element
result2 = list1.pop(2) # drop subscript 2
print(list1)
# 2. Remove ()
list2 = [11.22.33.44.55.33.33.55]
list2.remove(22)
print(list2)
Remove the first matched element in the list.
list2.remove(33)
print(list2)
# 3. Clea ()r clears the specified list into an empty list
list2.clear()
Copy the code
Other usage
- Reverse Reverses the list
- Sort () sort(sort internally, no new list generated)
- Censored () sort (creating a new list)
- Copy () is in the list
- List2 = list1 # No new memory space
- List2 = list1.copy() # create a new memory space
- Convert a list () a tuple ()
# 4. Other usage
# 4.1. Reverse, the reverse
list1 = [35.4.5.4.654]
print(list1[-1: : -1])
list1.reverse()
print(list1)
# 4.2.1sort, which defaults to ascending, sort within the list
Sort ()
list1.sort() # ascending
list1.sort(reverse=True) # descending
Sorted, sorted, default ascending, generates a new list
# sorted(list name)
newList = sorted(list1) # ascending
newList2 = sorted(list1, reverse=True) # descending
# 4.3 copy, copy
list1 = [23.54.56]
list2 = list1 # memory space is not recreated
list2[1] = 100
print(list1)
print(list2)
print(id(list1) == id(list2))
# copy, deep copy, heap space level
list1 = [23.54.56]
list2 = list1.copy() Respace the memory, but only the first layer
list2[1] = 100
print(list1)
print(list2)
print(id(list1) == id(list2))
# 4.4 conversion
# list(),tuple()
# 2-d list: traversal
l1 = [[11.22.33.44], [44.55.66]]
print(l1[0]) # l1[0] = [11, 22, 33, 44]
print(l1[0] [2])
for i in l1:
for j in i:
print(j)
Copy the code
The interview questions
list1 = [54.6.57.5.57.7.6.7.22.57.57.57.436]
Index # simulation
for i in range(len(list1)):
if list1[i] == 22:
print(i)
# count() counts the number of occurrences of the specified element in the list
print(list1.count(22)) Count the number of times 22 appears in the list
# delete all 57
for i in list1[:]: # Be careful here
if i == 57:
list1.remove(57)
print(list1)
Copy, copy(),deeepcopy()
Copy only copies the outermost layer of the contents. Deepcopy copies the inner layer of the contents.
a = [1.2.3]
b = [4.5.6]
c = [a, b]
d = copy.copy(c) Shallow copy, but with the parent reference
print(id(d) == id(c)) # False
e = copy.deepcopy(c) # deep copy
print(id(e) == id(c)) # False
a.append(4)
print(c) # [[1, 2, 3, 4], [4, 5, 6]
print(d) # [[1, 2, 3, 4], [4, 5, 6]] #
print(e) # [[1, 2, 3], [4, 5, 6]]
"" "d: [[1, 2, 3], [4, 5, 6]] [list1, list2] -- -- -- -- > list1: [1, 2, 3] list2: (4 and 6) "" ""
Copy the code
3.3 yuan group (a tuple)
Similar to a list, it is essentially an ordered collection (except that tuples are not added or deleted)
The difference between tuples and lists:
- Different definitions: list [] tuple ()
- Modifiable: A list can add or remove elements, but once a tuple has been defined, none of the elements can be changed
- Allows you to store duplicate elements, allows you to store different types of data
t1 = (1.1.2.3.4.5."Hello".False)
Copy the code
- When there is only one element in a tuple, it is recognized as a normal variable. We need to add a tuple name =(element,).
t = (10.)Copy the code
- Special case: If the element in the tuple is a list, the elements in the list can still be modified
T5 = (t5 = (t5 = (t5 = (t5 = (t5 = (t5)))23.5.3.5[235.345.5.45.4])
print(t5)
print(t5[4]) #,5,45,4 [235345]
t5[4] [1] = 100
print(t5)
Copy the code
- Other usage
# List and tuple traversal
Get the element directly
for element in t5:
print(element)
Select * from index;
for i in range(len(t5)):
print(i, t5[i])
Iterate over index and element at the same time
You need to convert a tuple or list to an enumeration type
# Note: the following I is not the index of a tuple or list, but the number in the enumeration
for i, element in enumerate(t5):
print(i, element)
Copy the code
check
Access to a tuple element
Tuple name [index]
print(t1[5])
Copy the code
3.4 the dictionary (dict)
Dictionary: Also a way to store data, but dictionaries are unordered (other methods are similar to lists).
Similar to lists or tuples, dictionaries store data in key-value pairs
Function: with extremely fast search speed
A key is equivalent to an index in a list or tuple
Key features:
- Dictionary keys are unique
- The key must be immutable data
List is mutable and cannot be used as a key
Tuples, data types, strings, and booleans are immutable and can be used as keys
dict1 = {"zhangsan": 10, "lisi": 13, "zhaoliu": 50}
Copy the code
check
- Dictionary name [“key”] If key does not exist, an error is reported
- Dictionary name. get(“key”) If key is not present, None is returned without an error
# 1. Access key/value pairs
print(dict1["lisi"])
If a key does not exist, an error is reported
# print(dict1["abc"]) #KeyError: 'abc'
# 2.get()
result1 = dict1.get("zhaoliu")
print(result1)
# return None if key does not exist
result2 = dict1.get("def")
print(result2)
Copy the code
change
- Dictionary name [key] = value
dict1["zhaoliu"] = 100result0 = dict1["zhaoliu"]print(result0)
Copy the code
increase
- Dictionary name [key] = value
If key exists, change value; Dict1 [" ABC "] = 20print(dict1)
Copy the code
delete
- Dict1. Pop (“key”
- Del dict1[“key”
- Del Dict1 Delete the whole dictionary
- Dict1. Empty the elements of the dictionary
Note: If the specified key is deleted, the corresponding value is also deleted
dict1.pop("lisi")dict1.clear() # dictdict1 [' dictdict1 '] # dictdict1 [' dictdict1 '] # dictdict1 [' dictdict1 '] # dictdict1 [' dictdict1 '] # dictdict1
Copy the code
Dictionary traversal
- Direct traversal is the key of traversal
- Dict. Values () value
- Enumerate (dict) Number and key
- Dict.items () traverses both keys and values
# 3 dictionary traversal
# 3.1 Directly traverse key mastery
for key in dict1:
print(key, dict1[key])
for key in dict1.keys():
print(key, dict1[key])
# 3.2 Directly traverse value
for value in dict1.values():
print(value)
# 3.3 iterates over the number and key of the key-value pair
for i, element in enumerate(dict1):
print(i, element)
# 3.4 Traverse key and value mastery simultaneously
for key, value in dict1.items():
print(key, value)
Copy the code
The interview questions
"" [Interview question: The difference between dict and list 】 1. The speed of dict lookup and insertion does not slow down as the number of key-values increases, while the speed of list is traversed from start to end every time it is searched. When there is a large amount of data, the speed of list will definitely slow down. A list only stores keys or values in a dictionary, and the list data is tightly packedCopy the code
# 1. List one by one, according to l1 = [" Sun ", "Mon, Tue, Wed," Thu ", "Fri", "Sat"] in the index for an odd number of elements
l1 = ["Sun"."Mon"."Tue"."Wed"."Thu"."Fri"."Sat"]
for i, index in enumerate(l1):
if i % 2! =0:
print(i, index)
# 2. The list will belong to l1 = [" Sun ", "Mon, Tue, Wed," Thu ", "Fri", "Sat"), but do not belong to the list of l2 = [" Sun ", "Mon", "Thu", "Fri", "Sat") is defined as all the elements of a list of new l3
l1 = ["Sun"."Mon"."Tue"."Wed"."Thu"."Fri"."Sat"]
l2 = ["Sun"."Mon"."Thu"."Fri"."Sat"]
l3 = []
for i in l1:
if i not in l2: Add I to l3 if I is not in L2
l3.append(i)
print(l3)
s = set(l1)
s1 = set(l2)
print(s ^ s1)
# 3. The list of known namelist = [' stu1 ', 'stu2', 'stu3', 'stu4', 'stu5', 'stu6', 'stu7], and delete list removelist = [' stu3', 'stu7', 'stu9]; Remove every element in the Removelist list from the Namelist (those belonging to removelist but not namelist are ignored).
namelist = ['stu1'.'stu2'.'stu3'.'stu4'.'stu5'.'stu6'.'stu7']
removelist = ['stu3'.'stu7'.'stu9']
for i in removelist:
if i in namelist: If it is inside, remove it with remove()
namelist.remove(i)
print(namelist)
A string is an English sentence. Count the frequency of occurrence of each word and generate a dictionary. The word is used as key and the frequency is used as value to generate a dictionary dict1
str1 = "today is a good day today is a bad day today is a nice day"
str2 = str1.split("") # Split by Spaces into lists
dict1 = {}
for i in str2:
c = dict1.get(i) # key: word value: number of times use.get();
if c == None:
dict1[i] = 1 # Add to dictionary
else:
dict1[i] += 1
print(dict1)
# 5. A list of known list1 =,1,2,3,4,5,6 [0], list2 = [" Sun ", "Mon, Tue, Wed," Thu ", "Fri", "Sat"), with elements in list1 as key, The element in list2 as value generates a dictionary dict2
list1 = [0.1.2.3.4.5.6]
list2 = ["Sun"."Mon"."Tue"."Wed"."Thu"."Fri"."Sat"]
Define a variable to be used as an index for list1 and list2
index = 0
dict2 = {}
if len(list1) == len(list2): # If two lists are of equal length
while index < len(list1):
dict2[list1[index]] = list2[index]
index += 1
elif len(list1) > len(list2): # If two lists are not equal in length
while index < len(list2):
dict2[list1[index]] = list2[index]
index += 1
else:
while index < len(list1):
dict2[list1[index]] = list2[index]
index += 1
print(dict2)
x = dict(zip(list2,list1))
Copy the code
3.5 set (set)
Set: no repetition of elements is allowed, and intersection and union operations are performed
Represents the relationship between {} and dict: The set stores only keys
Essence: An unordered collection of non-repeating elements
increase
- The add () to add
- A single element. If the added element exists, adding fails. No error is reported
- Multiple elements, added with add in a set, can only be added to tuples, not lists and dict
- Update the update ()
- Cannot be added directly. Arguments can be lists, tuples, dictionaries, etc.
# add();
set1 = {11.22.33.44.55}
# single element
set1.add(66)
set1.add(55) If the element to be added exists, the element will not be added
# multiple elements
# s1.add([77,88]) #TypeError: unhashable type: 'list'
s1.add((77.88))
# s1.add({1:"a"})
If you add a set, you can only add tuples, not lists and dict
# update(),update,update can only be iterable
set2 = {11.22.33.44.55}
# set2.update(66) # TypeError: 'int' object is not iterable
set2.update([66]) # []
set2.update((77.88)) # ()
set2.update({"12": 14."13": 13}) Only key will be added
set2.update("hgjhgaa") # add characters one by one (do not add duplicate characters)
Copy the code
delete
- Remove () An error occurs if the removed element does not exist.
- Discard () No error occurs if the deleted element does not exist.
- Pop () randomly removes an element from the collection
- Clear () clears the collection
set2.remove(77)set2.discard(33)set2.pop()set2.clear()
Copy the code
Intersection and union
# Intersection and union
s1 = {3.54.4.5.7}
s2 = {3.54.4.8.90}
# Intersection: &
print(s1 & s2)
# and sets: | "bitwise or"
print(s1 | s2)
rint(s1 ^ s2)
Copy the code
The interview questions
# Master: Remove duplicate elements from a list
s2 = set([3.46.5.65.7.65.7]) # []
s3 = set((2.43.54.5.4.5)) # ()
s4 = set({10: "a".20: "b"}) # dictionary, only ke
Copy the code
3.6 Differences and connections between list,tuple,dict, and set
- List [] tuple() dict{} set{}
- Ordered: list tuple
- Unordered: dict set
- Whether duplicate elements are allowed: list,tuple: dict:key not allowed,value yes, set not allowed
- All belong to the iterable
- A set stores keys in a dictionary
- They can convert to each other
4. Summary of Python functions
4.1. Basic usage of functions
4.4.1 concept
A function is a programming method of structuring or procedural program logic. It is an organized, reusable piece of code used to implement a single or identical function.
Function improves modularity of application points and code reuse
Essence: A function is a closure of a function
Formal parameter: a parameter for short, is essentially a variable with no value.
Actual arguments: arguments are essentially constants, variables, or expressions
Parameter passing: The process by which an argument is assigned to a parameter, and the type of the argument depends on the needs of the parameter
4.1.2 Function Definition
Def function name (arguments 1, 2, 3...) : Function body return Return valueCopy the code
Note:
A. Function naming follows the rules of identifiers, so as to know meaning by name, small hump naming,
B. Parameter 1, parameter 2, parameter 3….. Formal parameters. Different parameters are separated by commas (,). There is no limit on the number of parameters
C. Function body: encapsulated function
D, return: terminates the function, returns the value to the caller, or can be used alone
E. Return values can be constants, variables, or expressions
4.1.3 the return value
Return value: represents the result of the execution of a function
Note: For return statements with no arguments, None is returned
4.1.4 call
Function call: in essence is the process of function on and off the stack
That is, function pushing: the function is called; Function out of the stack: the function is called
Note: Be careful to avoid an infinite loop during a function call
4.1.5 Scope of variables
Scope of a variable: The scope within which a variable can be accessed
Division of scope:
L :(local) local scope, the innermost layer, contains local variables, such as the inside of a function/method.
E :(Enclosing) function scopes (closures),nonlocal(you must use this on closures)
G :(Global) Global scope, the outermost layer of the current script, such as the Global variable of the current module.
B :(built-in) scope, which contains built-in variables/keywords, etc. , and was finally searched
Rules for finding variables (same names of variables) :
If you want additional recommendations on this. In Python, the scope of variables is built_in B > global (glbal G) > external (glbal G) on functions > local (local L).
Note: Use the proximity rule when accessing variables within a function with the same name.
If the name of the global variable can be overwritten by the local variable when declared in a function body, we need to use global or nonlocal to declare the variable.
Global and local variables
total = 0 This is a global variable
Writable function description
def sum(arg1, arg2) :
# return the sum of 2 arguments.
total = arg1 + arg2 # total is a local variable here.
print("Inside the function are local variables:", total)
return total
Call the sum function
sum(10.20)
print("Outside the function are global variables:", total)
Copy the code
Global and nonlocal keywords
The global and nonlocal keywords are used when an inner scope wants to modify a variable in an outer scope
global
num = 1
def fun1() :
global num The global keyword is required
print(num) # 1
num = 123
print(num) # 123
fun1()
print(num) # 123, because global is used inside the function to modify the variable
Copy the code
Nonlocal (must be used in closures)
If you want to modify variables in a nested scope, you need the nonlocal keyword.
def outer() :
num = 10
def inner() :
nonlocal num # nonlocal keyword declaration
num = 100
print(num)
inner()
print(num) # 100 because local variables were modified with nonlocal
outer()
Copy the code
4.1.6 parameters
- Passing of parameters
Parameter passing has value passing and reference passing
- Value passing: Passing immutable types of data, such as num, STR,tuple, etc. In value passing, parameter changes do not affect the arguments
def check(s):
print(s)
print(id(s))
s = "i am test"
print(id(s))
return s
s = "This is a test"
print(check(s))
print(s)
Copy the code
-
Passing by reference: passing mutable types of data, such as list,dict,set, etc. Parameter changes affect the use of arguments
# reference-passing: When passing a list or dictionary, changing the value of a reference modifies the original object def check(l) : print(l) print(id(l)) l.append([1.23.2.3.4]) return ll = [1.2.3.4] print(check(l)) print(id(l)) "' [1, 2, 3, 4] 53235528 [1, 2, 3, 4, [1, 23, 2, 3, 4]] 53235528 ' ' ' Copy the code
Arguments in functions pass references to objects
-
Parameter type
-
Required arguments: The required arguments must be passed to the function in the correct order, and the number of calls must be the same as when they were declared.
def printme(str) : "Print any incoming string" print(str) returnCall printme function printme("aa" Copy the code
-
Keyword arguments: The order of arguments and parameters is allowed to be inconsistent, because the Python interpreter automatically matches keyword arguments based on their names
-
def show2(name, age): Print ("name:%s age:%d" % (name, age)) show2(name="jack", age=47) # Show2 (" Tom ", age=15) show2(" Tom ", age=15) show2(" Tom ", age=15) Def show3(a, b, c): Print (a, b, c) show3 show3 (1, 4, 4) (a = 3, c = 5, b = 5) show3 (45, b = 9, 18) c = # show3 (a = 45,9,18) # SyntaxError: positional argument follows keyword argumenCopy the code
- Default argument: When a function is called, the default value [default] is used if no argument is passed.
Def func3(name=" ABC ", age=18): Func3 () func3(" Jack ", 19) print("name:%s age:%d" % (name, age))Copy the code
-
Variable length arguments: Can handle more arguments than when declared
- *args, in the form of tuples
- ** Wkargs is in the form of dictionaries
def text(*args, **kwargs) : print(args) Accept one or more parameters print(kwargs) text(10.11, {"a": 1."b": 2}, x=12, y=13) """(10, 11, {'a': 1, 'b': 2}){'x': 12, 'y': 13}""" Copy the code
4.1.7 Anonymous Functions
Lambda expressions: Anonymous functions in Python handle encapsulation of simple logical expressions, using the lambda keyword
Advantages: No memory, improve the running speed of the code
The general format is:
Var = lambda args: expressionCopy the code
Such as:
Sum = lambda arg1, arg2: arg1 + arg2 print sum(10, 20) print ", sum( 20, 20 ))Copy the code
-
Ordinary anonymous function
abc = lambda a,b:a+bx = abc(5.5)print(x) Copy the code
-
Anonymous functions as arguments
Def func(x, y, func): def func(x, y, func): def func(x, y, func): def func(x, y, func)Copy the code
func(1, 2, lambda a, b: a + b))
3. 匿名函数与内置函数的结合使用
```python
list2 = [{'a': 10, 'b': 2}, {'a': 50, 'b': 3}, {'a': 1, 'b': 1}, {'a': 89, 'b': 1}]
# max()
m = max(list2, key=lambda x: x['a']) # 找列表嵌套字典,a的最大值
print(m)
# sorted() 升序
print(sorted(list2, key=lambda x: x["a"], reverse=True))
# filter() 条件 查找a大于10的
result = filter(lambda x: x["a"] > 10, list2)
print(list(result))
Copy the code
Reduce (function, sequence[, initial]) -> value
from functools import reduce
tuple1 = (3.4.6.1.2.3)
result = reduce(lambda x, y: x * y, tuple1, 50) Multiply each number in the tuple in turn
result2 = reduce(lambda x, y: x + y, tuple1, 50) # 3+4+6+1+2+3+50 add a 50
result3 = reduce(lambda x, y: x - y, tuple1, 10)
print(result, result2, result3)
Map (func, *iterables) --> map object func: function *iterables
# add 100 to the odd number in the list
result = map(lambda x: x if x % 2= =0 else x + 100, list1)
# loop over the list1 element, return itself if the element divided by 2 equals 0, otherwise add 100
print(list(result))
Copy the code
4.2. Function progression
4.2.1 Concepts [Special Usage]
-
Variables can point to functions
x = abs(-35) print(x) # 35 A normal variable can refer to a function, and that variable can be called as a function f = abs # ABC returns the absolute value of the argument print(f) print(f(-100)) def check() : print("check") check() f1 = check # where f1 is treated as a function call!! Do not use parentheses when assigning values f1() Copy the code
-
Functions can also be variable names
The function loses its original function
Print (abs(-28)) # abs = "hello" # print(abs(-7)) #TypeError: 'STR' object is not callableCopy the code
-
Functions are used as arguments
Passing a function as an argument to a function does not require parentheses
Call the function in the parameter, which must be the same as the original function def test(a, b, fun) : return fun(a) + fun(b) # abs(43) + abs(-27) print(test(43, -27.abs)) # fun = abs def test1(s1, s2, func) : return func(s1) + func(s2) print(test1("hello"."word".len)) # func=len do not use parentheses as arguments Copy the code
4.2.2 closure
Another function is defined inside a function, that is, there are external functions and internal functions
Condition:
2. The external function must have a return value. The return value is: internal function name 3. An inner function refers to a variable of an outer functionCopy the code
def func(a, b) : # 101, 99,
c = 100
def inner_func() : # 1. An inner function is defined in an outer function
D = 20
print("Closure", a + b + c + D) # 3. The inner function references the variables of the outer function
return inner_func # 2. The external function must have a return value, which is the name of the internal function (without parentheses).
x = func(101.99) The address of the internal function is received
x() Call an internal function
Copy the code
Advantages of closures: What are the disadvantages of a variable defined in an external function that can be accessed directly by an internal function? Disadvantages of closures (1), the scope is less intuitive (2), because variables are not garbage collected and therefore have some memory footprintCopy the code
What closures do:
-
Peer scopes can be used
-
Reads internal variables of other elements
-
Extended scope
Closure summary:
-
Closures seem to optimize variables so that they can do the work that class objects do.
-
Because closures refer to local variables of external functions, local variables of external functions are not freed with time, consuming memory
-
The benefits of closures make code concise and easy to read.
-
Closures are fundamental to understanding decorators
Holdings decorator
Decorator: Allows other functions to add functionality to a function without making any code changes. The return value of the Decorator is also a function.
Essence: The essence of a decorator is a closure that takes one function as an argument and returns another function
-
Decorator functions run when the function is defined
-
The decorator needs to return an executable object
-
The executable returned by the decorator should be compatible with the arguments of f
Decorator conditions:
2. The external function must have a return value. The return value is: internal function name 3. The inner function references the variables of the outer function. 4Copy the code
Use decorators:
Def function name (): passCopy the code
-
Simple decorator
References functions as arguments to outer functions in the context of closures
import time # decorator with parameters def zhuang1(func) : # accept f1 function as argument def wrapper(*args, **kwargs) : 1. The inner function is defined in the outer function print("Verifying.....") time.sleep(2) print("Verification completed.....") func(*args, **kwargs) 4. The function is used as the outer function argument return wrapper 2. The external function must have a return value, the return value is: internal function name @zhuang1 def f1() : print("I am the head of the household one------one") f1() Copy the code
-
A function with arguments
import time
# decorator with parameters
def zhuang1(func) : Receive # f1
def wrapper(*args, **kwargs) : # I'm going to add args, kwargs
print("Verifying.....")
time.sleep(2)
print("Verification completed.....")
Call the original function
func(*args, **kwargs)
return wrapper # return the decorator to F1
sum = 10000
@zhuang1
def f1(sum) :
print("I am the head of the household one------one".sum)
f1(sum)
@zhuang1
def f2(sum, name="abc") :
print("I am the householder {}-----two".format(name), sum)
f2(sum)
@zhuang1
def f2(sum, name="aaaaaa") :
print("I am the householder {}-----two".format(name), sum)
f2(sum, name="adfafasdasd") # overrides the value of name
Copy the code
-
Decorated functions have return values
Be sure to return the original function
If the decorator function returns a value, return the result of the decorator function
def say(func) :
def inner() :
print("-- -- -- -- -- -- -- -- -- -- 2")
return func() The function must be returned here
return inner
@say
def show() :
return "-- -- -- -- -- 1 -- -- -- -- --"
print(show())
Copy the code
- Use multiple decorators to decorate the same function
If the decorator is multi-level, whoever is closest to the function uses the decorator first.
def zhuangfeng1(func) : Define decorator 1
print("-----one---start")
def warper() :
print("Brush paint..")
return func() Return the original function
print("end")
return warper
def zhuangfeng2(func) : Define decorator 2
print("-----two---start")
def warper() :
print("Beat the hemp pepper...")
return func() Return the original function
print("end")
return warper
# Use decorators
@zhuangfeng2
@zhuangfeng1
def fz1() :
return "Householder one"
print(fz1())
"" "-- -- -- -- -- one -- -- -- -- -- -- - start end two - start end scutching pepper.. Brush paint.. The head of the household "" "
When multiple decorators are applied to the same function, they are executed from the top down, but the original function is called only once
Copy the code
-
Decorators take parameters
There are three layers
Decorators with Arguments Decorators with arguments are three layers: the first layer receives arguments to decorators; the second layer receives functions; the third layer receives arguments to functions.
def outer(a) : The first layer is responsible for receiving the decorator's parameters
def decorate(func) : # layer 2: responsible for receiving functions
def wraper(*args, **kwargs) : Layer 3: Buy a receiver function argument
func(*args, **kwargs)
print("-- > Floor tile {} block".format(a))
return wraper
return decorate
@outer(100) Decorator takes parameters
def house(time) :
print("I got the blank room on {} date".format(time))
house("2020-9-9")
Copy the code
4.2.4 partial function
By setting default parameters, you can make the call easier, as can partial functions
Concept: a function that does some control over its parameters
Note: Partial functions generally do not need to be defined themselves, but use the [functools module, which provides the use of partial functions]
import functools
def int2(x, base=2) :
return int(x, base)
print(int2("1011"))
print(int2("1010".8))
The functools module of the system provides the implementation of partial functions
# arguments: default arguments to existing function names
int3 = functools.partial(int, base=2)
print(int3("1110"))
print(int3("1110", base=10))
Idea: Based on an existing function, a new function is generated, called a partial function, by modifying the default values of the function parameters
Copy the code
4.3 higher-order functions
4.3.1 the filter () filtering
Filter (function,iterable) :function: an iterable
- You must return True and False because filter only evaluates True and False for retention
Filter (function,iterable) filters the elements of an iterable using certain conditions. Apply the function passed in to each element of the iterable in turn, depending on the Boolean value returned (True or False) to determine whether the element should be retained. If False is returned, the element needs to be filtered out.
Copy the code
Filter out the even numbers in the list
list1 = [1.2.3.4.5.6.7.8]
def func(num) :
# keep even elements
if num % 2= =0:
return True
# Filter odd elements
return False
The func function checks the values in the list1 list. If True is returned, the values are kept and added to the list. If False, discard
newList4 = list(filter(func, list1))
print(newList4)
# Remove the stats where hobbies are "none"
data = [['name'.'hobby'.'age'], ['tom'.'no'.10], ['jack'.'singing'.28]]
def func2(s) :
if s == "No":
return False
return True
for line in data:
result = list(filter(func2, line))
print(result)
Copy the code
4.3.2 the map () mapping
map(function,Iterable); Iterable: iterable
- The function object must have a return value
""" Map (function,Iterable) maps the specified sequence based on the Iterable function. Function: Iterable: Iterable how it works: This function takes each element of the sequence as an argument and returns a new list containing the functions of the function: Apply the passed function to each element in the sequence in turn and return the result as a new iterable.
""" Functions passed to map have the following requirements: a. arguments can have only one (by default, an iterable element is passed to the function) b. The letter"Copy the code
# Compute the square of each element in the list
list1 = [1.2.3.4.5]
# Method 1:
# map[def defined function]
def func(x) :
return x ** 2 There must be a return value
result = map(func, list1) Func returns the value of each element in the list
print(result)
newList4 = list(result)
print(newList4)
# Method 2: map[anonymous function]
newList5 = list(map(lambda x: x ** 2, list1))
print(newList5)
Copy the code
4.3.3 Reduce () iteration [accumulation]
Reduce (function,iterable) function: The processing to be performed on iterable iterable objects
- The function object must have a return value
- There must be two arguments in the function
Functools reduce(function,iterable): a function that accumulates elements in a sequence: Operate on the first and second elements of the sequence of functions passed to reduce, operate on the third element with the result, and the fourth element with the result... Example: f, [a, b, c, d] reduce (f,] [a, b, c, d) working principle: f (f (f (a, b), c) and d), similar to the recursion Is [1, 2, 3, 4] (((1 + 2) + 3) + 4) "" "
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'] """
Copy the code
from functools import reduce
Calculates the sum of the elements in a list of integers
【def define a function 】
def mySum(x, y) :
return x + y The function must set the return value
result0 = reduce(mySum, list1)
print(result0)
"" "mySum (1, 2) -- - > 3 mySum (3, 3) -- -- -- -- > 6 mySum (6, 4) -- - > 10 mySum (10, 5) -- - > 15 "" "
# 2: reduce[anonymous function]
result1 = reduce(lambda x, y: x + y, list1)
print(result1)
Copy the code
The interview questions
from functools import reduce
Convert [1,3,5,7,9] to the integer 13579
list1 = [1.3.5.7.9]
def func(num, y) : The function must take two arguments
return (num * 10) + y There must be a return value
new = reduce(func, list1)
print(new)
Copy the code
from functools import reduce
Int (xx); int(xx);
def charToNum(s) :
# Define the mapping between strings and integers
digits = {'0': 0.'1': 1.'2': 2.'3': 3.'4': 4.'5': 5.'6': 6.'7': 7.'8': 8.'9': 9}
return digits[s] Return the key corresponding to the dictionary
def func(num, y) : The function must take two arguments
return (num * 10) + y
# Demand: "24356" ------ 24356
# a. Generate a mapping
r0 = list(map(charToNum, "243567890")) Add the returned value to the list
print(r0)
# b. Use reduce accumulation
r1 = reduce(func, r0)
print(r1)
print(type(r1))
Copy the code
Object orientation in Python
5.1 Basic usage of object Orientation
5.1.1 concept
Process oriented: specific, process, to solve a problem, need step by step analysis, step by step implementation.
Object oriented: modeling, the real things abstracted as attributes or functions in the program, and they do not need to manage the process of method realization in the model, only need to call.
The bottom line of object orientation is actually process orientation
Object – oriented three characteristics :1. Encapsulation 2. Inheritance 3. Polymorphism
The advantages and disadvantages:
Process-oriented:
- Advantages: Performance is better than object-oriented, because classes need to be instantiated when called, and memory overhead is high
- Disadvantages: not easy to maintain, not easy to reuse, expansion
Object-oriented:
- Advantages: easy maintenance, easy reuse, easy to expand
- Disadvantages: High memory overhead, poor performance compared to process-oriented
Class: A class is an abstraction of objects. It abstracts properties or behaviors from concrete things in real life. As methods or properties in programs, classes are abstract
Object: An object is an instance of a class that creates a concrete object in the real world
5.1.2 Defining a class
A class is made up of attributes and methods
1. Properties: Common property, private property __
Define classes and attributes
class Student:
name = "Xiao Li" # attribute
age = 20
__phone = 123 # private attributes
You = Student()
print(You.name)
print(You.age)
You.age = 18
print(You.age)
You.set = "Female" # create your own
print(You.set)
Copy the code
2. Method: ordinary method class method static method magic method
-
Common methods
Definition: The first argument must be an instance object, usually named “self”, through which to pass instance properties and methods (or class properties and methods);
Call: Can only be called by instance objects.
Format:
defThe function name () : pass Copy the code
class Phone:
brand = "Millet" # attribute
price = 1999
type = "mate 90"
The common method in the Phone class is call
def call(self) :
print("self---->", self) # refers to the current class object
print("My phone is :{},{},{}".format(self.brand, self.price, self.type)) Use self to access attributes in a class
print("Accessing address book :")
for i in self.addbook: # Access external attributes
print(i)
print("On the phone")
print("Message:", self.note) # Access external attributes
p1 = Phone()
p1.note = "I'm the note for Phone1." # Add attributes
p1.addbook = [{1001: "Zhang"}, {1002: "Bill"}]
p1.call()
Copy the code
-
Class method
Definition: Use the decorator @classMethod. The first parameter must be the object of the current class, whose name is conventionally “CLS”, through which to pass attributes and methods of the class (not instance attributes and methods);
Call: Both instance objects and class objects can be called.
""" classmethod characteristics: 1. Definition needs to rely on the decorator @classmethod 2. The parameter in a class method is not an object, but CLS 3. Only class attribute 4 can be used in a class method. Def show1(CLS, b=" ABC ") def show1(CLS, b=" ABC ") def show1(CLS, b=" ABC ") CLS (" class method -->").eat() # CLS.__age = 200 # CLS.
Copy the code
class Dog:
a = "abc" # class attribute
def __init__(self, name) : # init method
self.name = name
def run(self) :
print("{} running".format(self.name))
def eat(self) : The normal method takes the argument self
print("{} is eating".format(self.name))
self.run() Call a normal method in a class
@classmethod
def show(cls, a="dfg") : @classMethod (CLS)
print("I'm a class method {}".format(a))
print(cls) # <class '__main__.Dog'>
@classmethod Class methods are called with CLS. Class method names ()
def show1(cls, b="abc") :
print("I'm class method 2{}".format(b))
cls.show() Call a class method in a class method
cls("Class method -->").eat() Change the pass-through parameter of the normal method
c = Dog("Flower")
c.run() # Common method
c.eat()
print(c.a) Get an attribute from the class
c.show1()
DFG
DFG
DFG
```
```python
class Person:
__age = 18
def show(self) :
print("- >", Person.__age)
@classmethod
def update_age(cls) :
cls.__age = 200 Use class methods to modify private attributes
print("I'm the modified class method.")
@classmethod
def show_age(cls) :
print("I'm a modified class method.", cls.__age)
cls().show()
a = Person()
a.show()
a.update_age()
a.show_age()
""" --> 18 I am a modified class method. I am a modified class method.
Copy the code
- A static method
Static methods: very similar to class methods 1. Requires a decorator @staticMethod 2. Static methods need to pass arguments (CLS,self) 3. Only class properties and methods can be accessed; object properties cannot be accessed 4. Load time class methods static methods can call ordinary methods without self, they can call class methodsCopy the code
class Person:
__age = 18
def show(self) :
print("- >", Person.__age)
def show1() :
print("123456676767867")
@classmethod
def update_age(cls) :
cls.__age = 200 Use class methods to modify private attributes
print("I'm the modified class method.")
@classmethod
def show_age(cls) :
cls.update_age()
print("I'm a modified class method.", cls.__age)
@staticmethod
def test() :
print("I'm a static method")
Person.show_age() Static methods can call class methods
# person.show () # Static methods cannot call ordinary methods with self inside
Person.show1() If there is no self in it, it can be called
s = Person.__age
print("I am the class property of the call", s)
a = Person()
a.test()
""" I am static method I am modified class method I am modified class method 200 123456676767867 I am calling class attribute 200 ""
Copy the code
-
Magic methods
Magic method a magic method is a method in a class/object, and the only difference is that ordinary methods need to be called! When a magic method is triggered: when the object is initialized (not instantiated, but in the same operation as instantiated) 2.__new__: 3.__call__: object call method trigger time: when an object is used as a function, the content of this function will be called by default. 4. Del p1 removes references to addresses. When a space is empty of references, del is executed by default. Note: Be sure to add a return to the __str__ method. The content after the return is what the print object sees. Copy the code
class Person:
def __init__(self, name) : Initialize the object
print("---->init", self)
self.name = name
def __new__(cls, *args, **kwargs) : When executing a function, execute new first, before init()
# new does not need to be called
print("--->new")
nc_new = object.__new__(cls)
print("I am the memory address of the new magic method.", nc_new)
return nc_new
def __call__(self, name) : When an object is used as a function, the contents of this function are called by default
print("Call the object's current function with -->call")
print("Execute object gets argument :", name)
p = Person("aa") #
p("x") When an object is used as a function, the contents of this function are called by default
Copy the code
P = Person1() p1 = p Delete address reference del p1 delete address reference 3 from P1 to Person1. Import sys sys. getrefCount (p) 4 When a space is empty of references, del "" is executed by default.
import sys
class Person1:
def __init__(self, name) :
self.name = name
def __del__(self) :
print("I am del method")
p = Person1("CCTV")
p1 = p
p2 = p
print(sys.getrefcount(p))
del p1 Delete address references. When a block of space has no references, the default execution is del
print(sys.getrefcount(p))
Copy the code
# __str__
class Person2:
def __init__(self, name, age) :
self.name = name
self.age = age
def __str__(self) : The toString method is overridden in Java
return "Name:" + self.name + "Age:" + str(self.age)
p = Person2("tom".20)
print(p)
# Print the name of the object
If you want to give the developer more information when printing object names, override the STR method
Copy the code
conclusion
Static methods can only access ordinary methods without SLEF. Static methods access class methods by class name. CLS access class methods. 2. Class methods have arguments (CLS), static methods have no arguments the same: 1. Only class attributes and methods can be accessed, but object attributes cannot be accessed. Both can be used before creating an object, because the object is not dependent on the normal method and the difference between the two: difference: 1. No decorator 2. Ordinary methods always depend on objects, because every ordinary method has a self 3. A normal method can only be called if the object is created, otherwise it cannot be called.Copy the code
5.2 Three Features of Object Orientation
Object – oriented features: encapsulation, inheritance, polymorphism
5.2.1 encapsulation
Packaging:
- Privatization attributes
- Define public set and GET methods
Format: __ Attributes (private attributes): Attributes are privatized and access is restricted to the class
Benefits:
- Hidden properties cannot be modified by outsiders
- If you want to change it you have to change the set get method
To encapsulate an instance is to privatize the attribute
Def setXXX(self,name): # setXXX(self,name): # setXXX(self,name): # setXXX(self,name) Return self.__xxx """
Copy the code
class Student:
def __init__(self, name, age) :
self.__name = name # private attributes
self.__age = age
self.__scort = 99
Set and get methods
def setName(self, name) : Set the length of name to 6 bits or less
if len(name) <= 6:
self.__name = name
else:
print("Incorrect name input.")
def getName(self) :
return self.__name
def __str__(self) : #
return Name: {}, age: {}, grade: {}".format(self.__name, self.__age, self.__scort)
p = Student("李小".20)
p.setName("ffff") # set is used to modify
print(p.getName()) # get is used to get
print(p)
Copy the code
1. Methods to access private properties
Method 1: Set and get methods
class Student:
def __init__(self, name) :
self.__name = name
def setName(self, name) : Set the length of name to 6 bits or less
if len(name) <= 6:
self.__name = name
else:
print("Incorrect name input.")
def getName(self) :
return self.__name
p = Student("李小")
p.setName("ffff") # set is used to modify
print(p.getName()) Get private attributes
Copy the code
Method two: the way to use decorators
@property # is just get
def a() :
pass
@a.setter # is set
def b() :
pass
Copy the code
class Student:
def __init__(self, name, age) :
self.name = name
self.__age = age
# Get, set
@property
def age(self) : # is just get
return self.__age
@age.setter
def age(self, age) : # is actually set
if age > 0 and age < 100:
self.__age = age
else:
print("Input error")
def __str__(self) :
return Name: {}, age: {}".format(self.name, self.__age)
s = Student("Xiao Li".20)
print(s.age) Get private attributes
print(s)
Copy the code
Method three: pass _ class __ private attribute names
class Stu(object) :
def __init__(self) :
self.__age = 99
s = Stu()
print(s._Stu__age) # accessed by _ class name __ private property name
# View the properties of the created object
print(dir(s)) # Check the properties inside
print(s.__dir__()) Dir (p) = dir(p
Copy the code
conclusion
Summary: Encapsulation is the privatization of attributes,
Method 1: define set and get methods.
Method two: use decorator @property(get), @method name. Setter (set)
Method 3: you can use _ class name __ private attribute name to access the private genus of a class
Use dir(), or the object name.dir(), and look at the properties inside
5.2.2 inheritance
One of the main benefits of object-oriented programming is code reuse, and one way to achieve this reuse is through inheritance mechanisms.
A new class created by inheritance is called a subclass or derived class, and the inherited class is called a base class, parent class, or superclass. Python is not reloaded, only overridden………..
Single inheritance syntax
Class Derived class name (base class name)...Copy the code
Some features of subclass inheritance in Python:
-
1. If __init__ is not defined in the class, the super class __init__ 2 is called by default. If the class inherits its parent class and needs to define its own __init__, call _init__ of the parent class from __init__ of the current class: init 3. Override: Call method 5 of the subclass if it overrides the method of the parent class. A subclass can call the superclass method super(). Method name (argument)
6. Private attributes that can only be accessed in your own class. But you can call methods in the parent class that use private attributes. Properties in a method are the parent class’s own private properties
class Person: Parent class, base class
def __init__(self, name, age) :
self.name = name # a king
self.age = age # 30
self.__phone = "123"
def run(self) :
print("{} running.... {}".format(self.name, self.__phone))
def eat(self) :
print("{} eat....".format(self.name))
class Student(Person) : If you inherit from the parent class, you get all of its methods and attributes.
def __init__(self, name, age, sex) : # almost overrides the constructor
super().__init__(name, age) # use attributes defined by the parent class, inheriting attributes from the parent class
self.age = 99
self.sex = sex
A wavy line is an error
def eat(self, food) : # override the eat method on the parent class. Python only overrides it
super().run() Call the parent class's eat method
print("{} is eating {},{},{}".format(self.name, food, self.sex, self.age))
Person("A king".30)
stu = Student("Xiao Li".20."Male")
stu.eat("Shit")
print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -" * 2)
Copy the code
Verify that subclasses can access private attributes of their parent class
# 1. You can only use private attributes in your own class
class Person1:
def __init__(self, sex) :
self.sex = sex
self.__money = 200
self.name = "abc"
def show1(self) :
print("I am the superclass show{}, {}".format(self.__money, self.name))
class Student2(Person1) :
def __init__(self, sex) :
super(Student2, self).__init__(sex) # Use super() to access common attributes in the parent class
self.__money2 = 500 Private property, accessible only in this class
self.name = "deg"
super().show1() # use super().show1() to access methods in the parent class that use private attributes
def show(self) :
print(self.__money2, "-- -- -- -- -- -", self.sex) # access private attributes of the parent class
class Stu3(Person1) :
def __init__(self, sex) :
super(Stu3, self).__init__(sex)
def show(self) :
print(self.name, = "-- -", self.sex) Access the ordinary properties of the parent class
s = Student2("Male")
s.show()
s3 = Stu3("A woman")
s3.show()
""" I am the parent class of show200, DEG 500 ------ male ABC --=- female """
Copy the code
If more than one class is listed in an inheritance tuple, it is called “multiple inheritance”.
Multiple inheritance syntax:
The declaration of derived classes, like their parent classes, follows the list of inherited base classes, as follows:
class SubClassName (ParentClass1[, ParentClass2, ...] ) :...Copy the code
Class A(oobject) class A(oobject) class A(oobject) class A(oobject) class A(oobject) class A(oobject) ' ' '
# Depth-first: When calling class A test function, as shown in the figure below, first look for the test function in class A, then look for class B, then look for class D, and finally look for class C. python2
# A-->B-->D-->C
# breadth-first: When calling the test function of class A, as shown in the figure below, first look for the test function of class A, then look for class B, then look for class C, and finally look for class D. python3
# A-->B-->C-->D
class D: Object is inherited by default
def test(self) :
print("D")
class C(D) :
def test(self) :
print("C")
class B(D) :
pass
# def test(self):
# print("B")
class A(B, C) :
pass
# def test(self):
# print("A")
a = A()
a.test()
# check the execution order
print(A.__mro__)
import inspect
print(inspect.getmro(A))
Copy the code
conclusion
Conclusion: Inheritance is when a subclass inherits its parent class
-
Has a: Use a custom type, system type
-
Is a: subclass (superclass), a subclass cannot inherit the private attributes of its parent, private attributes may be used in its own class
-
Multiple inheritance: breadth first (python3), depth first (python2)
Mro or import inspect print(inspect.getmro)
5.2.3 requires polymorphism
What polymorphism does in Python: It allows functions with different functions to use the same function name, so that functions with different content (function) can be called with the same function name
Inheritance is a prerequisite for polymorphic implementation
Benefits of polymorphism: Improved code reuse
Features of polymorphism in Python
1. We only care about whether the instance method of the object has the same name, not the type of the object. 2. The inheritance relationship between the classes to which the object belongs is optional; 3. The benefits of polymorphism can increase the flexibility of the external call of the code, making the code more general and more compatible; 4. Polymorphism is a technique for calling methods and does not affect the internal design of classes.Copy the code
Polymorphism:
Expression of polymorphism in Java: polymorphism can be understood as a variety of forms of a thing. Python also supports polymorphism, but with limited support for polymorphism, mainly because python uses variables without declaration, so there is no parent class reference to a polymorphic representation of a subclass object, and Python does not support overloading. The use of polymorphism is not as obvious in Python as it is in Java, so it doesn't make much sense to talk about polymorphism deliberately in PythonCopy the code
import abc
class Animal(metaclass=abc.ABCMeta) : # Same thing: animals
@abc.abstractmethod
def talk(self) :
pass
class Cat(Animal) : # One of the animal forms: cat
def talk(self) :
print('say miaomiao')
class Dog(Animal) : # Animal Form 2: dog
def talk(self) :
print('say wangwang')
class Pig(Animal) : # Animal Form # 3: pig
def talk(self) :
print('say aoao')
c = Cat()
d = Dog()
p = Pig()
def func(obj) :
obj.talk()
func(c)
func(d)
func(p)
"""
say miaomiao
say wangwang
say aoao
"""
Copy the code
It’s basically calling the same method and getting different results
conclusion
Conclusion: Python is not strictly polymorphic, because it does not have the access modifier in Java, so it can be accessed, but we can use isintance() to check whether the object isin a class.Copy the code
5.2.4 Singleton mode
Singleton: a common software design pattern whose main purpose is to ensure that only one instance of a class exists.
Singletons come in handy when you want only one instance of a class in the entire system.
You just want to have one instantiation object in a class. Otherwise, multiple memory resources will be wastedCopy the code
class Person: Create an object space, save it, and use the object space you created last time
__instance = None
# override the __new__ method
def __new__(cls) : # execute before init
if cls.__instance is None:
cls.__instance = object.__new__(cls) # give the first created address to __instance
return cls.__instance
else:
return cls.__instance
Cls.__instance (); cls.__instance (); cls.__instance (); cls.__instance ()
__instance is not empty after new, so else return address first created. So it's always the same address
p = Person()
p1 = Person()
print(p, p1)
Copy the code