Python study notes (to be continued)

1. Basic knowledge

A computer program tells the computer in great detail the sequence of steps needed to complete a task.
Hardware Physical computers and peripherals are collectively referred to as hardware.
Software A program executed by a computer.
Programming The activity of designing and implementing computer programs.

The core of the computer is the central processing unit (CPU) . The CPU executes program control and data processing, that is, the CPU locates and executes program instructions, performs arithmetic operations such as addition, subtraction, multiplication, and division, and reads data from external memory or devices and stores processed data. .

There are two types of storage devices, namely primary storage and secondary storage. Main memory consists of memory sticks, electronic circuits that store data when powered. Secondary storage provides cheap and low-speed storage capacity, and can be saved for a long time in the event of power failure. Among them, the hard disk is a relatively common auxiliary storage.

Computers store both data and programs. Data and programs are stored in the auxiliary storage and loaded into the memory when the program is executed. The program updates the data in the memory and writes the modified data back to the auxiliary storage.

Environment variable: refers to a set of parameters in the operating environment specified by the operating system, which contains information used by one or more applications. Environment variables are generally multi-valued, that is, an environment variable can have multiple values. For operating systems such as Windows and Linux, they all have a system-level environment variable PATH (path). When the user asks the operating system to run an application without specifying the full path of the application, the operating system will first search for the application in the current path, and if it cannot find it, it will search for it in the path set specified by the environment variable PATH . If it is found, it will be executed, otherwise, an error message will be given, and the user can specify the location where the program runs by setting the environment variable.

Quick check of python knowledge points

insert image description here
insert image description hereinsert image description here
insert image description here

Chinese processing

If the script contains Chinese (Chinese comments or Chinese strings, Chinese strings should be preceded by u), then the encoding needs to be indicated in the file header, and the script must also be saved as UTF-8 encoding

# -*- coding: utf-8 -*
print u'世界,你好!'

2. Install and configure Python

Introduction to Python

Python is a high-level scripting language that combines interpretability, compilation, interactivity, and object-oriented.

Python is designed to be highly readable. Compared with other languages, it often uses English keywords and some punctuation marks in other languages. It has more distinctive grammatical structures than other languages.

Python is an interpreted language: this means that there is no compilation part of the development process. Similar to PHP and Perl languages.

Python is an interactive language: this means that you can execute code directly after a Python prompt >>>.

Python is an object-oriented language: This means that Python supports an object-oriented style or programming technique in which code is encapsulated in objects.

Python is a beginner's language: Python is a great language for beginning programmers, supporting a wide range of application development, from simple word processing to WWW browsers to games.

Python interpreter

A Python program consists of one or more lines of instructions or statements that can be translated and executed by the Python interpreter.
The Python program is interpreted and executed by the Python interpreter, which reads the program and executes it.

Features of Python language
Simple syntax, cross-platform, extensible, open source, rich class library

History of Python

In 1990, Python was born.
In 2000, Python2.0 was released.
In 2008, Python3.0 was released.
In 2010, python2.7 was released (the last 2.X version).

Python source code and documentation

Python's latest source code, binary documents, news information, etc. can be viewed on Python's official website:

Python official website: https://www.python.org/

You can download the documentation for Python at the link below, and you can download the documentation in HTML, PDF, and PostScript formats.

Python document download address: https://www.python.org/doc/

Install Python on Windows platform

The following are the simple steps to install Python on the Windows platform:

Open the WEB browser and visit https://www.python.org/downloads/windows/

Select the Windows platform installation package in the download list, the package format is: python-xyz.msi file, xyz is the version number you want to install.

To use the installer python-xyz.msi, the Windows system must support Microsoft Installer 2.0. Just save the installation file to your local computer, then run it to see if your machine supports MSI. There is already an MSI for Windows XP and later, and many older machines can also install the MSI.

After downloading, double-click the download package to enter the Python installation wizard. The installation is very simple. You only need to use the default settings and click "Next" until the installation is complete .

Environment variable configuration
Set environment variables in Windows
1. Add the Python directory to the environment variables:

In the command prompt box (cmd): enter

path=%path%;C:\Python Press "Enter".
Note: C:\Python is the installation directory of Python.

2. It can also be set in the following ways:

Right-click "Computer", then click "Properties"
, then click "Advanced System Settings",
select "Path" under the "System Variables" window, and double-click it!
Then in the "Path" line, just add the python installation path (my D:\Python32), so just add this path later. ps: Remember, the path is directly separated by a semicolon ";"!
After the final setting is successful, enter the command "python" on the cmd command line to display the relevant information.

Start Python from IDLE : IDLE is a Python shell, and a shell is a way to interact with a program by typing text. After opening, as shown in the figure below:
insert image description here

3. Using Python for the first time

The difference between several important data types

String objects are immutable.
List data items do not need to have the same type. Elements of
tuples can be modified. Dictionaries cannot be modified. Elements of
dictionaries are mutable and can store objects of any type.
A collection (set) is an unordered non-repetitive A sequence of elements, you can use braces { } or the set() function to create a set, note: to create an empty set, you must use set() instead of { }, because { } is used to create an empty dictionary

python comments

Explain the code, do not participate in the operation
Code line: #
Code line: control+/ (# shortcut key)
Comments in the function: '''/"""

print statement

Syntax:
print(value1,value2,…,valuen)

#All parameters are optional, if no parameters are specified, a blank line will be output The
first Python program

print("Hello World!")   #在屏幕上输出  Hello World!

Note: Python is case sensitive.

Python can be used as a calculator
insert image description here
to achieve string concatenation with + and string repetition with *
insert image description here

Write a guessing number game

print("......你好......")
temp = input("你来猜猜我心里想的是哪个数字:")
guess = int(temp)
if guess == 6:
	print("哇!你也太棒了吧!")
	print("你怎么知道我心里想的什么?")
else:
	print("啊哦!我现在心里想的是6!")
print("游戏结束,下次再玩")

Built-in functions (BIF == Built-in functions)
How to check which built-in functions are available in Python?
Enter in the shell, dir(__builtins__)where the pure lowercase is BIF.
insert image description here
How to check the function of BIF?
Take input as an example, enter in the Shell help(input)to view the function of the input
insert image description here

4. Variables and strings

variable

Example of variable assignment:
insert image description here
Note:
1. Before using a variable, it needs to be assigned a value.
2. The variable name can include letters, numbers, and underscores, but the variable name cannot start with a number.
3. Case-sensitive, such as a and A for Python Said to be two completely different names
4. The equal sign (=) means assignment, the left side is the variable name, and the right side is the value of the variable, which cannot be written in reverse

string

insert image description here
1+1 is completely different from "1"+"1"

Note:
1. Single quotes ' or double quotes " must appear in pairs
2. If you want to print Let's go!
Method 1: print("Let's go!")
Method 2: Use the escape character (\) to escape the quotes in the string:print('Let\'s go!')
insert image description here

raw string

1. You can escape yourself with a backslash
2. Add an English letter r in front of the string
insert image description here

long string

If you want to get a string that spans multiple lines, you need to use triple-quoted strings !
For example, the following poem is output:
Maoyan Yuanweijue,
Zhuwa Ou Prophet.
Forgotten to sleep in the cold,
the window is so bright that you can peep repeatedly.
insert image description here

5. Commonly used operators

comparison operator

insert image description here

Python's conditional branch syntax (if...else...)

if 条件:
	执行语句    #条件为真(True)执行的操作
else:
	执行语句    #条件为假(False)执行的操作

Section 3 game code should enter

print("......你好......")
temp = input("你来猜猜我心里想的是哪个数字:")
guess = int(temp)
if guess == 6:
	print("哇!你也太棒了吧!")
	print("你怎么知道我心里想的什么?")
else:
	if guess > 6:
		print("猜大啦!")
	else:
		print("猜小咯!")
print("游戏结束,下次再玩")

while loop


while 条件:
	执行语句   #条件为真时执行

Add the while loop:

print("......你好......")
temp = input("你来猜猜我心里想的是哪个数字:")
guess = int(temp)
while guess != 6:
	temp = input("哎呀,猜错了,请重新的输入:")
	guess = int(temp)
	if guess == 6:
		print("哇!你也太棒了吧!")
		print("你怎么知道我心里想的什么?")
	else:
		if guess > 6:
			print("猜大啦!")
		else:
			print("猜小咯!")
print("游戏结束,下次再玩")

logical operator

Logical operators can connect arbitrary expressions together to obtain a Boolean value.

and (and) when both sides are true, the result is true (True)
or (or) as long as one of the conditions on both sides is true, it is true
not (not) is the opposite of the result
a and b if x is False, then a and b Returns False, otherwise returns the calculated value of y
a or b If x is not 0, returns the value of x, otherwise returns the calculated value of y
not x If x is True, returns False; if x is False, returns True
insert image description hereinsert image description here

random module

There is a function in the random module called: randint(), which returns a random integer

Adapt the game using randint():

import random
secret = random.randint(1,10)
print("......你好......")
temp = input("你来猜猜我心里想的是哪个数字:")
guess = int(temp)
while guess != secret:
	temp = input("哎呀,猜错了,请重新的输入:")
	guess = int(temp)
	if guess == secret:
		print("哇!你也太棒了吧!")
		print("你怎么知道我心里想的什么?")
	else:
		if guess > secret:
			print("猜大啦!")
		else:
			print("猜小咯!")
print("游戏结束,下次再玩")

6. Python data types

basic data type

Integer (int)
Float (float)
String (str)
Boolean (bool)

PS: e notation (10e5 represents 10 to the 5th power)
insert image description here

Data Type Conversion

Integer: int()
Float: float()
String: str()

Example of converting floating-point type to integer type: (directly intercept the integer part) Example
insert image description here
of converting integer type to floating-point type :
insert image description here
converting integer type to string type Example:
insert image description here

Use the type() function to get the data type

insert image description here

Use the isinstance() function to determine the data type

insert image description here

7. Python common operators

+= -= *= /

a +=1 is equivalent to a = a+1
a -=1 is equivalent to a = a-1
a =1 is equivalent to a = a 1
a /=1 is equivalent to a = a/1

% // **

Find the remainder of a%b , the remainder of a divided by b
a//b is rounded, the quotient of a divided by b is
a**b power operation, a to the power of b
insert image description here

priority

insert image description here

The precedence of () > not > and > or
insert image description here
** is special, higher than the unary operator on the left and lower than the unary operator on the right
insert image description here

8. Branch and loop 1

Playing plane frame:

Load background music
Play background music (set up a single cycle)
Our plane is born
interval = 0
while True:
if the user clicks the close button:
exit the program
interval +=1
if interval ==50
interval = 0
The small plane is born
and the small plane moves One position
screen refresh
if the user's mouse moves:
the center position of our plane = the user's mouse position
screen refresh
if there is a physical conflict between our plane and a small plane:
we hang up and play collision music
modify the pattern of our plane
print "Game Over"
Stop background music, preferably fade out

9. Branch and Loop 2

conditional expression (ternary operator)

x,y = 4,5
if x<y:
small = x
else:
small = y
相当于:
small = x if x<y else y

assert

insert image description here

10. Branch and loop 3

while loop

grammar:

while 条件:
	循环体
	

for loop

grammar:

for 目标 in 表达式:
	循环体

Example:
insert image description here
insert image description here
enumerate(sequence, [start=0])
sequence – a sequence, iterator or other object that supports iteration.
start – The starting position of the subscript.
The enumerate() function is used to combine a traversable data object (such as a list, tuple or string) into an index sequence, and list data and data subscripts at the same time, generally used in for loops.
insert image description here

seq = ['a','b','c','d']
for index,key in enumerate(seq):
    print('seq [{0}] = {1}'.format(index,key))
#输出
#seq [0] = a
#seq [1] = b
#seq [2] = c
#seq [3] = d

range() function

insert image description here
Example:
insert image description here
Only one parameter in the range() function is used in combination with for:
(starts from 0 by default)
insert image description here
Only two parameters in the range() function are used in combination with for:
(the default step is 1)
insert image description here
There are only three parameters in the range() function Combined with for:
insert image description here

break与continue

break Terminates the current loop (jumps out of the loop body)
continue Terminates the current loop and jumps to the start position of the loop The judgment condition determines whether to start the next loop
Example:
break
insert image description here
continue
insert image description here

11. List list (1)

how to create a list

1. Create a normal list
insert image description here
2. Create a mixed list
insert image description here
3. Create an empty list
insert image description here

How to add elements to a list

append()

There is only one parameter, the parameter is the element to be inserted, only one element can be added at a time (default is added to the end) insert image description here
Note: append() can only add one element
insert image description here

extend()

There is only one parameter, the parameter is the element to be inserted, extend() can add multiple elements at a time, but the parameter must be a list, (default is added to the end)
insert image description here

insert()

There are two parameters in insert(a,b), the first parameter represents which position (subscript) in the list to insert the element, and the second parameter represents what element to insert

insert image description hereinsert image description here

12. List list (2)

How to get an element from a list

insert image description here

How to swap the order of elements in a list

Example: Swap the first and third elements
insert image description here

How to remove an element from a list

remove()

The argument is the element value, not the position of the element
insert image description here

of the()

The parameter is the position
insert image description here
del list name of the element to delete the entire list

pop()

The pop() method takes out the last element from the list by default, and returns
insert image description here
the element at the specified position.
insert image description here
pop vs. remove

pop removes the element corresponding to the index position, that is, the element position needs to be provided, and the element value is returned at the same time

remove removes the first matching element in the list, that is, the value of the element to be removed needs to be provided, and there is no return value

List slice (slice)

insert image description hereinsert image description here

13. List list (3)

built-in functions for lists

insert image description here

comparison operator

insert image description here
![Insert picture description here](https://img-blog.csdnimg.cn/20200810165022399.png

logical operator

insert image description here

list concatenation

Use + to splice several lists together
insert image description here
Note:
+ cannot add new elements
insert image description here

list repeat

insert image description here
insert image description here

membership operator

in element a in list list
(return True if it exists, otherwise return False)
not in element a not in list list
(return True if not in list, otherwise return False)
insert image description hereinsert image description here

Access the elements of a list within a list

insert image description here

count()

Counts the number of times an element (argument) occurs in a list
insert image description here

index()

The position where the return parameter first appears in the list
insert image description here
can also specify a range , for example, the specified range (4, 7), the position where 1 first appears in this range
insert image description here

reverse()

Reverse the elements in the list, no parameters are required by default
insert image description here

sort() and sorted()

sort()
sorts the list members according to the specified method. By
default, no parameters are required. The default is to sort the elements from small to large.
insert image description here
How to sort from large to small? An example is as follows:
insert image description here
using the built-in method sort() of the list to sort the list will modify the data of the list itself, but the global built-in function sorted() is different, it will copy a copy of the original list, and then perform a sorting operation on the copy. The original list remains unchanged.

Supplement on the concept of "copy" of shards

insert image description here

insert image description here
Conclusion:
Fragment "copy" is only equivalent to a backup copy, and the change of the original list will not cause the list of the fragment "copy" to change.
The method of directly assigning the original list name to the new list name "copy" is equivalent to the new list also pointing to the The original list, the change of the original list will also cause the change of the new list

List comprehensions (and dictionary and set comprehensions)

1. List comprehension
Syntax: [generate expression for variable in sequence or iterative object]

The following two pieces of code function the same

aList = [x**2 for x in range(4)]
print('aList:',aList)
#输出aList: [0, 1, 4, 9]
aList = []
for x in range (4):
    aList.append(x**2)
#输出aList: [0, 1, 4, 9]

1. Filter the unqualified elements in the original sequence
(example: extract the integers in a list and square them)

a_list = [1,'4',9,'a',0,5,'hello']
squared_ints = [e**2 for e in a_list if type(e) == int]
print('squared_ints:',squared_ints)         #squared_ints: [1, 81, 0, 25]

2. Use list comprehension to realize the tiling of nested lists
(using two layers of for loops to tile nested lists into a list example)

vec = [[1,2,3],[4,5,6],[7,8,9]]
flat_vec = [num for elem in vec for num in elem]
print(flat_vec)         
#[1, 2, 3, 4, 5, 6, 7, 8, 9]

This list comprehension includes two for loops. The first for loop can be regarded as an outer loop, and the second for loop can be regarded as an inner loop. Each time the outer loop reads an element (an inner list element, such as [1 ,2,3]), the inner loop needs to traverse three sub-elements in the list element (such as 1, 2, 3), obviously, the outer loop runs slowly, but the inner loop runs fast, the num at the front of the square brackets, is the output expression.
3. Combining multiple conditions to construct a specific list
(the following list comprehension integrates the elements in two different lists together). It
should be noted that if the expression is a tuple, such as (x, y) in the first line, then it must bracket it

new_list = [(x,y) for x in [1,2,3] for y in [3,1,4] if x != y]
print(new_list) 
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

2. Dictionary derivation
The use of dictionary derivation and list derivation is similar, except that [] in the list needs to be changed into curly braces {}

mcase = {
    
    'a':10,'b':30,'c':50}
kv_exchange = {
    
    v:k for k,v in mcase.items()}
print(mcase.items())
#dict_items([('a', 10), ('b', 30), ('c', 50)])
print(kv_exchange)
#{10: 'a', 30: 'b', 50: 'c'}

Three, collection derivation

squared = {
    
    x**2 for x in [1,1,2,-2,3]}
#对每个元素实施平方操作
print(squared)#集合可以达到去重的效果,输出{1, 4, 9}

14. Tuple (unchangeable data type)

Create and access a tuple

insert image description here
() is not an iconic symbol for judging tuples
insert image description here

, (comma) is an iconic symbol for judging tuples

insert image description here
insert image description here
repeating tuple
insert image description here

How to create an empty tuple?
insert image description here

update and delete a tuple

To update and delete members of a tuple, you can use the method of + splicing (the data types on both sides of the splicing must be consistent)
insert image description here
to delete the entire tuple
del tuple name

15. String operation (1)

Fragmentation

insert image description here

Update and delete using splicing method

insert image description here

String Methods and Comments

find(sub[, start[, end]])
detects whether sub is included in the string, and returns the index value if yes, otherwise returns -1. The start and end parameters indicate the range, which are optional.

insert image description here

index(sub[, start[, end]]) Same as the find method, but raises an exception if sub is not in string.
insert image description here

capitalize() Change the first character of the string to uppercase
insert image description here
casefold() Change all characters of the entire string to lowercase
insert image description here
center(width) Center the string and fill it with spaces to a new string of length width
insert image description here

count(sub[, start[, end]]) returns the number of occurrences of sub in the string, the start and end parameters indicate the range, optional.

insert image description here

encode(encoding='utf-8', errors='strict') encodes the string in the encoding format specified by encoding.

endswith(sub[, start[, end]])
Checks whether the string ends with the sub substring, returns True if it is, otherwise returns False. The start and end parameters represent the range, optional.

insert image description here

expandtabs([tabsize=8]) Convert the tab symbol (\t) in the string into spaces. If no parameter is specified, the default number of spaces is tabsize=8.
insert image description here
isalnum() returns True if the string has at least one character and all characters are letters or numbers, otherwise returns False.
insert image description here

isalpha() returns True if the string has at least one character and all characters are alphabetic, otherwise returns False.
insert image description here

isdecimal() Returns True if the string contains only decimal digits, otherwise returns False.
isdigit() Returns True if the string contains only numbers, otherwise returns False.
isspace() Returns True if the string contains only spaces, otherwise returns False.
islower() Returns True if the string contains at least one case-sensitive character and those characters are all lowercase, otherwise returns False.
istitle() Returns True if the string is titled (all words start with uppercase and the rest are lowercase), otherwise returns False.
isupper() Returns True if the string contains at least one case-sensitive character and those characters are all uppercase, otherwise returns False.
join(sub) Use a string as a delimiter to insert between all the characters in sub.
bright(width) Returns a left-aligned string, padded with spaces to a new string of length width.
isnumeric() Returns True if the string contains only numeric characters, otherwise returns False.
lower() Converts all uppercase characters in a string to lowercase.
lstrip() Remove all whitespace from the left of the string
partition(sub) Find the substring sub, divide the string into a 3-tuple (pre_sub, sub, fol_sub), if the string does not contain sub, return ('original string', '', '')
replace(old, new[, count]) Replace the old substring in the string with the new substring, if count is specified, no more than count times.
rfind(sub[, start[, end]]) Similar to the find() method, but searches from the right.
rindex(sub[, start[, end]]) Similar to the index() method, but starts from the right.
rjust(width) Returns a right-aligned string, padded with spaces to a new string of length width.
rpartition(sub) Similar to the partition() method, but searches from the right.
isnumeric() Returns True if the string contains only numeric characters, otherwise returns False.
rstrip() Remove spaces from the end of the string.
splitlines(([keepends])) Whether to remove newline characters in the output result, the default is False, does not include newline characters; if it is True, newline characters are retained. .
split(sep=None, maxsplit=-1) Without parameters, the default is to slice strings with spaces as separators. If the maxsplit parameter is set, only maxsplit substrings will be separated, and a list of spliced ​​substrings will be returned.
upper() Converts all lowercase characters in a string to uppercase.
zfill(width) Returns a string of length width, the original string is right-aligned, and the front is filled with 0.
title() Returns the titled (all words start with uppercase and the rest are lowercase) string.
strip([chars]) Delete all the spaces before and after the string, the chars parameter can customize the characters to be deleted, optional.
swapcase() Flips case in a string.
translate(table) Transform the characters in the string according to the rules of the table (can be customized by str.maketrans('a', 'b')).
startswith(prefix[, start[, end]]) Checks if the string starts with prefix and returns True if so, otherwise returns False. The start and end parameters can specify range checking, optional.

16. String formatting

位置参数
insert image description here
关键字参数
insert image description here
如果混用位置参数与关键字参数,位置参数必须放置关键字参数前面

"{a} love {1}".format(a="I","you")
#输出 SyntaxError: positional argument follows keyword argument
 "{0} love {b}".format("I",b="you")
 #输出 'I love you'

字符串格式化符号含义

%c 格式化字符及其 ASCII 码
insert image description here
%s 格式化字符串
%d 格式化整数
insert image description here
%o 格式化无符号八进制数
insert image description here
%x 格式化无符号十六进制数
%X 格式化无符号十六进制数(大写)

insert image description here
%f格式化浮点数字,可指定小数点后的精度
%e用科学计数法格式化浮点数
%E作用同 %e,用科学计数法格式化浮点数

insert image description here%g根据值的大小决定使用 %f 或 %e
%G作用同 %g,根据值的大小决定使用 %f 或者 %E

insert image description here

格式化操作符辅助命令

insert image description here
insert image description here
insert image description here

Python 的转义字符及其含义

insert image description here

17.序列

内置方法

insert image description here
list()把一个可迭代对象转换为列表

list() 无参数 ,新建一个空列表
list(iterable) 有参数,(iterable是一个迭代器)
insert image description here
tuple([iterable])把一个可迭代对象转换为元组
insert image description here
str(obj) 把obj对象转换为字符串
len(sub)返回sub的长度
max()返回序列或参数集合中的最大值
min()返回序列或参数集合中的最大值
max()、min()中的参数类型必须一致
insert image description hereinsert image description here
sum(iterable[,start=0]) 返回序列iterable和可选参数start的总和
sorted() 使用方法与list.sort()一样
insert image description here

(注意) reversed(seq)

seq – 要转换的序列,可以是 tuple, string, list 或 range。

# 字符串
seqString = 'Runoob'
print(list(reversed(seqString)))
 
# 元组
seqTuple = ('R', 'u', 'n', 'o', 'o', 'b')
print(list(reversed(seqTuple)))
 
# range
seqRange = range(5, 9)
print(list(reversed(seqRange)))
 
# 列表
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))

['b', 'o', 'o', 'n', 'u', 'R']
['b', 'o', 'o', 'n', 'u', 'R']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]

enumerate() 函数

enumerate(sequence, [start=0])
用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

insert image description here
enumerate()在for循环中的使用
例1

i = 0
tuple = ("a",1,'b',2)
for element in tuple:
    print(i,tuple[i])
    i+=1
输出
0 a
1 1
2 b
3 2

例2

tuple = ("a",1,'b',2)
for i,element in enumerate(tuple):
    print(i,element)
输出
0 a
1 1
2 b
3 2

zip()

insert image description here

18&19.函数

insert image description here
函数的返回值用return语句返回
insert image description here

形参与实参

insert image description here

关键字参数

insert image description here

默认参数

定义了默认值的参数,调用时如果没有传递参数,会自动使用默认参数
insert image description here

可变参数

insert image description here
可变参数+其他的参数,后面的参数要用关键字参数访问,否则会出错,最好把其他函数定义为默认参数
insert image description here

20.函数(二)

局部变量与全局变量

正确代码:

def discounts(price,rate):
    final_price = price*rate
    return final_price
old_price = float(input("请输入原价:"))
rate = float(input("请输入折扣率:"))
new_price = discounts(old_price,rate)
print("打折后的价格是:",new_price)
    

insert image description here
试图输出局部变量:(错误代码)
insert image description here
试图输出全部变量:(不会报错)
insert image description here
insert image description here
global 关键字

insert image description here

内嵌函数

insert image description here

闭包

insert image description here

nonlocal关键字

(同global使用方式一样,但两者不等价)
insert image description here

21&22.lambda表达式

一个参数
insert image description here
两个参数
insert image description here

filter()

insert image description here
insert image description here

map()

insert image description here

23&24&25.递归

求阶乘

非递归方法求阶乘:

def factorial(n):
    result = n
    for i in range(1,n):
        result *= i
    return result

number = int(input("请输入一个正整数:"))
result = factorial(number)
print("%d 的阶乘是:%d" % (number,result))
输出
请输入一个正整数:5
5 的阶乘是:120

递归方法求阶乘:

def factorial(n):
    if n==1:
        return 1
    else:
        return n*factorial(n-1)

number = int(input("请输入一个正整数:"))
result = factorial(number)
print("%d 的阶乘是:%d" % (number,result))
输出
请输入一个正整数:5
5 的阶乘是:120

斐波那契数列

迭代(非递归)程序:

def F(n):
    n1 = 1
    n2 = 1
    n3 = 1
    if n<1:
        print("输入错误!")
        return -1
    while (n-2)>0:
        n3 = n1+n2
        n1 = n2
        n2 = n3
        n -=1
    return n3
result = F(20)
if result != -1:
    print("总共有%d对小兔子!"% result)
总共6765对小兔子诞生!

递归程序

def F(n):
    if n<1:
        print("输入有误!")
        return -1
    
    if n==1 or n==2:
        return 1
    else:
        return F(n-1)+F(n-2)

result = F(20)
if result != -1:
    print("总共%d对小兔子诞生!" % result)
总共6765对小兔子诞生!

汉诺塔

#n个盘子,3个柱子,从左到右依次是X,Y,Z
def hanoi(n,x,y,z):  
    if n==1:
        print(x,'-->',z)
    else:
        hanoi(n-1,x,z,y)#将前n-1个盘子从x移动到y上
        print(x,'-->',z)#将最底下的最后一个盘子从x移动到z上
        hanoi(n-1,y,x,z)#将y上的n-1个盘子移动到z上

n = int(input('请输入汉诺塔的层数:'))
hanoi(n,'X','Y','Z')

输出结果如下:
请输入汉诺塔的层数:3
X --> Z
X --> Y
Z --> Y
X --> Z
Y --> X
Y --> Z
X --> Z

26&27.字典

创建和访问字典

格式:、
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字。(不能是列表类型,因为列表是可变的)
insert image description here

fromkeys()

创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
insert image description here

keys()&values()&items()

insert image description here
clear() 清空字典

pop(key[,default])
删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。

popitem()
随机返回并删除字典中的最后一对键和值。

radiansdict.get(key, default=None)
返回指定键的值,如果键不在字典中返回 default 设置的默认值

radiansdict.copy()
返回一个字典的浅复制

radiansdict.update(dict2)
把字典dict2的键/值对更新到dict里

28.集合&29文件

如何创建一个集合
1.直接把一堆元素用花括号括起来
2.使用set()函数
insert image description here
insert image description here

唯一性
insert image description here
add()方法 & remove()方法
insert image description here

不可变集合frozenset

insert image description here
例题(考察集合推导式):把不合格的数据删除,或把实际相同但描述不同的对象(比如名字大小写不同)合并,假定有如下列表:
names = [‘Bob’,‘JOHN’,‘alice’,‘bob’,‘ALICE’,‘J’,‘Bob’]
现在我们要求将姓名长度小于2字符的删除(通常姓名的字符长度大于3),将写法相同但大小写不一样的名字合并,并按照习惯变成首字母大写,对于上面的列表,我们希望得到的结果如下:
{‘Alice’,‘Bob’,‘John’}

names = ['Bob','JOHN','alice','bob','ALICE','J','Bob']
name_1 = {
    
    name[0].upper()+name[1:].lower() for name in names if len(name)>2}
print(name_1)
#{'Bob', 'John', 'Alice'}

29.文件

系统函数open()

Python中的 open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

注意:
使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。

open(file, mode='r')
#open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)
#返回值是stream

完整的语法格式为:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
#file: 必需,文件路径(相对或者绝对路径)。
#mode: 可选,文件打开模式
#buffering: 设置缓冲
#encoding: 一般使用utf8

mode格式

r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
t 文本模式 (默认)。

file 对象

file对象使用 open 函数来创建,下表列出了 file 对象常用的函数:

file.close() 关闭文件。关闭后文件不能再进行读写操作。
file.read([size]) 从文件读取指定的字节数,如果未给定或为负则读取所有。
file.readline([size]) 每次读取一整行,包括 “\n” 字符。
file.readlines([sizeint]) 读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。
file.seek(offset[, whence]) 移动文件读取指针到指定位置
file.write(str) 将字符串写入文件,返回的是写入的字符长度。
file.writelines(sequence) 向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

读操作举例

读取E盘文本文件python-record.txt
insert image description here
解决方案如下:
insert image description here

stream = open("E:\\python-record.txt",'r',encoding = 'utf-8')
container = stream.read()              
print(container)

运行结果如下:
insert image description here

试图读word文件会报错(默认是文本文件)insert image description here
关闭文件之后不可以再读
insert image description here
readable() 判断文件是否是可读的

stream = open("E:\\python-record.txt",'r',encoding = 'utf-8')          
result = stream.readable()   #判断是否可读
print(result)
#输出True(可以读取E:\\python-record.txt文件,前提:文件存在)

readline()读取整行,包括 “\n” 字符

stream = open("E:\\python-record.txt",'r',encoding = 'utf-8')          
line = stream.readline()     #读取整行,包括 "\n" 字符
print(line)
#输出第一行和一行空行

用readline()读取全部文本

stream = open("E:\\python-record.txt",'r',encoding = 'utf-8')          
while True:
    line = stream.readline()
    print(line)
    if not line:
        break

stream.close()
#输出全部文本内容,每输出一行内容,下面都会输出一行空行

readlines()读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。

stream = open("E:\\python-record.txt",'r',encoding = 'utf-8')          
lines = stream.readlines()
print(lines)
   
stream.close()

运行结果:
insert image description here
可以读图片,但是不能显示图片,格式用 二进制形式读 即格式是 'rb’
如果是图片不能使用默认的读取方式,应该mode=‘rb’

写操作举例

1 、在E盘存在一个python-test.txt文件,里面内容是 666

stream = open("E:\\python-test.txt",'r',encoding = 'utf-8')
print(stream.read())
#读取文件内容
#输出 666

2、在上面的基础上(即文件中有内容666)进行 W 操作


stream = open("E:\\python-test.txt",'w',encoding = 'utf-8')
s = '''
你好!
         明天你有时间吗?
'''
result = stream.write(s)
print(result)

stream.close()

(w操作会把原来文本内容清除,然后写入新的内容)运行结果如下insert image description here
3、在2基础上(未关闭文件的情况下)再写入一个内容


stream = open("E:\\python-test.txt",'w',encoding = 'utf-8')
s = '''
你好!
         明天你有时间吗?
'''
result = stream.write(s)
print(result)

w2 = stream.write("有时间")
print(w2)

stream.close()  #释放资源

insert image description here
多次写操作在关闭文件之前
多次写,直接追加在原文本里
insert image description here

文件复制和OS模块

文件复制:复制一个文件


#把原文件 E:\girl.jpg (原文件在E盘已经存在)  复制到目标文件 D:\girl.jpg

with open("E:\\girl.jpg","rb") as stream: #此格式自动关闭文件,后面不需要close()
      container = stream.read()  #读取原文件内容

      with open("D:\\girl.jpg","wb") as wstream:
            wstream.write(container)
print("复制完成!")
#输出: 复制完成!(此时打开D盘可以发现已复制的文件girl.jpg)

文件复制:复制一个文件夹
上面方法不可用,上面是复制一个文件

os模块(里面包含许多函数)
使用os模块里面函数前先导入os模块
insert image description here
获取当前文件所在的文件目录(输出绝对路径)
insert image description here
把E:\girl.jpg---->保存在当前文件所在的目录下
错误代码
错误原因path定位的是一个文件夹,而open只能定位文件
insert image description here
正确代码

#文件复制

#把E:\girl.jpg---->保存在当前文件所在的目录下,并修改文件名为aaa.jpg

import os
with open("E:\\girl.jpg","rb") as stream: #此格式自动关闭文件,后面不需要close()
      container = stream.read()  #读取原文件内容

      path = os.path.dirname(__file__) #获取当前文件所在的文件夹目录
      path1 = os.path.join(path,"aaa.jpg")  #即在当前文件所在的文件目录后拼接aaa.jpg,并返回一个新的文件目录给path1,(在当前文件所在的文件目录下新建aaa.jpg文件)
      with open(path1,"wb") as wstream:
            wstream.write(container)
print("复制完成!")

当不知道要复制文件的文件名时,只知道路径,怎么从路径中获取文件名,并把该文件复制到本地文件夹下

#文件复制

#把E:\girl.jpg---->保存在当前文件所在的目录下

import os
with open("E:\\girl.jpg","rb") as stream: #此格式自动关闭文件,后面不需要close()
      container = stream.read()  #读取原文件内容
      print(stream.name)    #输出路径
      file = stream.name
      filename = file[file.rfind("\\")+1:] #截取文件名
      
      
      path = os.path.dirname(__file__)  #获取当前文件所在的文件夹路径
      path1 = os.path.join(path,filename)
      with open(path1,"wb") as wstream:
            wstream.write(container)
print("复制完成!")

相对路径与绝对路径

absolute 绝对的 (完整的路径) 例C:\User\programs
os.path.isabs(path) 判断是否为绝对路径
insert image description here相对路径:以当前路径为参照
前提:E盘下有两个文件夹分别是 image-test和log ,其中image-test下有一个girl.jpg文件,log里面有一个a1.txt文件

同级 ,找log同级的image-test中的image

r = os.path.isabs('image-test/girl.jpg')
print(r)
#找跟log同级的image-test里面的girl.jpg

insert image description here
上级 a1.txt上级的log的同级image-test下的girl.jpg

r = os.path.isabs('../image-test/girl.jpg')
print(r)
#../代表返回当前文件的上一级log

insert image description here
具体例子:

import os
#输出当前文件所在文件夹路径D:\Python\Python37\file01
path = os.path.dirname(__file__)
print(path)   
'''
还可以用以下方法获取当前文件所在文件夹路径
path = os.getcwd()
print(path)

'''

#通过相对路径得到绝对路径 D:\Python\Python37\file01\aa.txt
#aa.txt 与 本文件 a.py是兄弟,所以不用返回是上一级
path1 = os.path.abspath('aa.txt')
print(path1)


#通过相对路径得到绝对路径D:\Python\Python37\image-test\girl.jpg
#girl.jpg 是在当前文件a.py上一级file01的同级image-test里面
path2 = os.path.abspath("../image-test/girl.jpg")
print(path2)

#获取当前文件的绝对路径D:\Python\Python37\file01\a.py
path3 = os.path.abspath(__file__)
print(path3)

os.path常用函数

os.path.split(path)

#获取当前文件名(前面已讲过filename = path[path.rfind('\\')+1:])
#以下方法也可以
path = r'D:\Python\Python37\image-test\girl.jpg'
result1 = os.path.split(path)
print(result1)       
#输出一个元组('D:\\Python\\Python37\\image-test', 'girl.jpg')
print(result1[1])#输出girl.jpg

os.path.splittext(path)

#获取当前文件类型(分割文件与文件扩展名)
path = r'D:\Python\Python37\image-test\girl.jpg'
result2 = os.path.splitext(path) #分割文件与文件扩展名
print(result2)  #输出('D:\\Python\\Python37\\image-test\\girl', '.jpg')


os.path.getsize(path)

#获取文件大小(单位是字节)
path = r'D:\Python\Python37\image-test\girl.jpg'
size = os.path.getsize(path)
print(size) #输出59559

os.path.join(path,‘file’…)
参数1是路径,参数2、3…是要拼接的文件名

#在当前文件所在文件夹后拼接文件
path = os.getcwd()
print(path)     
#输出D:\Python\Python37\file01
result3 = os.path.join(os.getcwd(),'file','qq.jpg')
print(result3)  
#输出D:\Python\Python37\file01\file\qq.jpg

文件夹操作(00)

import os
dir = os.getcwd()
print(dir) #输出D:\Python\Python37\file02


all = os.listdir(r"D:\Python\Python37\file01")#返回指定目录下的所有文件和文件夹,保存到列表中
print(all)
#输出['a.py', 'aa.txt']

创建一个文件夹

#创建文件夹(先判断是否存在同名文件夹)
if not os.path.exists(r'D:\Python\Python37\file02\new'):
      f = os.mkdir(r'D:\Python\Python37\file02\new')
      print(f)
      #输出None,但此时打开file02会发现新创建的new文件夹

删除一个文件夹
os.rmdir()只能删除一个空的文件夹

#删除一个文件夹,只能删除一个空的文件夹
result = os.rmdir(r'D:\Python\Python37\file02\new')
print(os.path.exists(r'D:\Python\Python37\file02\new'))#输出False
#下面文件夹file03下面有文件,所以报错
result1 = os.rmdir(r'D:\Python\Python37\file02\file03')
#OSError: [WinError 145] 目录不是空的。: 'D:\\Python\\Python37\\file02\\file03'

删除非空文件夹file03

#删除非空文件夹file03
path = 'D:\\Python\\Python37\\file02\\file03'
filelist = os.listdir(path)
print(filelist)  #输出['11.txt', 'qq.txt']


for file in filelist:
      path1 = os.path.join(path,file)
      os.remove(path1)#删除文件
else:
      os.rmdir(path)

print('删除成功!')
#输出 删除成功!
#这是打开file02会发现file03已被删除

切换目录

#切换目录
path1 = os.getcwd()
print(path1)  #输出D:\Python\Python37\file02

f = os.chdir(r'E:\bootdo')#切换目录
path2 = os.getcwd() 
print(path2)  #输出  E:\bootdo

文件夹复制
file01里都是文件,没有文件夹

#把原文件夹 D:\Python\Python37\file01复制到目标文件夹D:\Python\Python37\file02
import os
src_path = r'D:\Python\Python37\file01'
target_path = r'D:\Python\Python37\file02'

#定义copy函数,参数分别是原文件夹和目标文件夹
def copy(src,target):
      if os.path.isdir(src) and os.path.isdir(target):#判断是否是文件夹
            filelist = os.listdir(src) #返回指定目录下(src下)的所有文件和文件夹,返回的是列表形式
            print(filelist)  #输出src下所有文件和文件夹['a.py', 'aa.txt']

            for file in filelist:#一次读写一个文件,利用for循环读写所有文件
                  path = os.path.join(src,file)#open读的是文件,
                  with open(path,'rb') as rstream:
                        container = rstream.read()#读文件里的内容放在container里

                        path1 = os.path.join(target,file)#文件名不变的复制到target里
                        with open(path1,'wb') as wstream:
                              wstream.write(container)
            else:#所有文件读写完成
                  print("复制完成!")
                              
#调用函数
copy(src_path,target_path)

如果file01里存在文件夹(00)

暂放

29文件(一)

文件打开与读取
insert image description here

fileObject.seek(offset[, whence])
#offset -- 开始的偏移量,也就是代表需要移动偏移的字节数,如果是负数表示从倒数第几位开始。
#whence:可选,默认值为 0。给 offset 定义一个参数,表示要从哪个位置开始偏移;0 代表从文件开头开始算起,1 代表从当前位置开始算起,2 代表从文件末尾算起。
#如果操作成功,则返回新的文件位置,如果操作失败,则函数返回 -1。

insert image description here
将E盘文件(python-record.txt)中的数据进行分割并按照以下规律保存起来:
1小明的对话单独保存为boy_.txt的文件(去掉小明说:")
2小红的对话单独保存为girl_
.txt的文件(去掉小红说:")
3文件总共有三段对话,分别保存为boy_1.txt, girl_1.txt, boy_2.txt, girl_2.txt, boy_3.txt, girl_3.txt共6个文件(提示:文件中的不同对话已经使用"======"分割)

f = open(r"E:\python-record.txt",'r',encoding = 'utf-8') #打开目标文件

boy = []
girl = []
count = 1

for each_line in f:
      if each_line[:6] != '======':
            #分割字符串
            (role,line_spoken) = each_line.split(":",1)#注意文本里的:是中文
            if role == '小明':
                  boy.append(line_spoken)
            if role == '小红':
                  girl.append(line_spoken)
      else:
            #字符串分别保存
            file_name_boy = 'boy_'+str(count)+'.txt'
            file_name_girl = 'girl_'+str(count)+'.txt'
            
            boy_file = open(file_name_boy,'w')
            girl_file = open(file_name_girl,'w')

            boy_file.writelines(boy)
            girl_file.writelines(girl)

            boy_file.close()
            girl_file.close()

            boy = []
            girl = []
            count += 1
            #前两段已保存
file_name_boy = 'boy_'+str(count)+'.txt'
file_name_girl = 'girl_'+str(count)+'.txt'
            
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')

boy_file.writelines(boy)
girl_file.writelines(girl)

boy_file.close()
girl_file.close()

boy = []
girl = []
count += 1
f.close()

insert image description here
该进代码

def save_file(boy,girl,count):
      file_name_boy = 'boy_'+str(count)+'.txt'
      file_name_girl = 'girl_'+str(count)+'.txt'
            
      boy_file = open(file_name_boy,'w')
      girl_file = open(file_name_girl,'w')

      boy_file.writelines(boy)
      girl_file.writelines(girl)

      boy_file.close()
      girl_file.close()
def split_file(file_name):     
      f = open(r"E:\python-record.txt",'r',encoding = 'utf-8') #打开目标文件
      boy = []
      girl = []
      count = 1

      for each_line in f:
            if each_line[:6] != '======':
                  #分割字符串
                  (role,line_spoken) = each_line.split(":",1)#注意文本里的:是中文
                  if role == '小明':
                        boy.append(line_spoken)
                  if role == '小红':
                        girl.append(line_spoken)
            else:
                save_file(boy,girl,count)
                boy = []
                girl = []
                count += 1
                  #前两段已保存
      save_file(boy,girl,count)#保存第三段
      f.close()#f.close() 应与for下载同一级别,否则缩进错误ValueError: I/O operation on closed file.

split_file("python-record.txt")

30.模块

模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py。模块可以被别的程序引入,以使用该模块中的函数等功能。

os模块

insert image description here

os.path模块

insert image description here

32.pickle模块

pickle提供了一个简单的持久化功能。可以将对象以文件的形式存放在磁盘上。

pickle模块只能在python中使用,python中几乎所有的数据类型(列表,字典,集合,类等)都可以用pickle来序列化,

pickle序列化后的数据,可读性差,人一般无法识别。
insert image description here
读取时用’rb’ 如果内容为空,会报错:EOFError: Ran out of input
insert image description here
insert image description here
把字典city,写成pickle
insert image description here

33&34异常处理

常见错误类型举例

AssertionError 断言语句(assert)失败
AttributeError 尝试访问未知的对象属性
insert image description here
IndexError 索引超出序列的范围
insert image description here
KeyError 字典中查找一个不存在的关键字
insert image description here
NameError 尝试访问一个不存在的变量
insert image description here

try-except语句

格式:

try:
	检测范围
except Exception[as reasion]:
	出现异常(Exception)后的处理代码

insert image description here

try:
      with open(r'D:\111111.txt') as f:
            print(f.read())
except OSError as reason:
      print('文件出错啦!\n出错的原因是:'+ str(reason))
#输出
#文件出错啦!
#出错的原因是:[Errno 2] No such file or directory: 'D:\\111111.txt'
try:
      sum = 1+'1'#程序在某处检测到错误,剩下的语句不会执行
      with open(r'D:\111111.txt') as f:
            print(f.read())
except OSError as reason:
      print('文件出错啦!\n出错的原因是:'+ str(reason))
except TypeError as reason:
      print('类型出错啦!\n出错的原因是:'+ str(reason))
#输出
#类型出错啦!
#出错的原因是:unsupported operand type(s) for +: 'int' and 'str'

try-finally语句

try:
	检测范围
except Exception[as reason]:
	出现异常(Exception)后的处理代码
finally:
	无论如何都会执行的代码

insert image description here
1.txt中并没有写入内容,因为f.close()之前的sum = 1+'1’出现异常,所以f.close()没有被执行,即1.txt写入的内容没有保存,该进代码如下:

try:
      f = open(r'D:\Python\Python37\1.txt','w')
      print(f.write('aaa'))
      sum = 1 + '1'
      
except TypeError as reason:
      print('类型出错啦!\n出错的原因是:'+ str(reason))
finally:
      f.close()
#输出
#3
#类型出错啦!
#出错的原因是:unsupported operand type(s) for +: 'int' and 'str'

raise语句

35.else语句与with语句

insert image description here
用with语句打开文件,默认关闭,可以避免忘记关闭文件
格式:

with oopen("文件地址",'r') as f:

36.图形用户界面入门:EasyGui

没下载

37&38.介绍对象

对象 = 属性 + 方法
类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。

**方法:**类中定义的函数。

**类变量:**类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。

数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据。

方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。

局部变量:定义在方法中的变量,只作用于当前实例的类。

**实例变量:**在类的声明中,属性是用变量来表示的,这种变量就称为实例变量,实例变量就是一个用 self 修饰的变量。

**继承:**即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类,这是模拟"是一个(is-a)"关系(例图,Dog是一个Animal)。

实例化:创建一个类的实例,类的具体对象。

对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。

类定义的格式:

class ClassName:        #类名的第一个字母大写。
    <statement-1>
    .
    .
    .
    <statement-N>
#类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性。

self代表类的实例,而非类

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。即类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。(self 不是 python 关键字,我们把他换成 aaa 也是可以正常执行的)

class Test:
    def p(self):
        print(self)
        print(self.__class__)
 
t = Test()
t.p()
#输出
#<__main__.Test instance at 0x100771878>
#__main__.Test

从以上执行结果可以很明显的看出,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。

class A:
      name = 'a'
      def f1(self,name):
            self.name = name
            print(self.name)
      def f2(self):
            #self.__class__指向类A,self.__class__.name相当于A.name
            print(self.__class__.name)
      def f3(self,args):
            self.__class__.name = args
            print(self.__class__.name)
a = A()#实例化对象a
a.f1('qq') #把参数qq传入f1方法中,并输出

a.f2() #输出A.name

a.f3('QQ')#通过f3修改A.name的值

b = A()
b.f2()#输出QQ,因为上面a.f3('QQ')把A.name的值修改了

insert image description here
insert image description here

init(self)

insert image description here

公有与私有

在Python中定义私有变量只需要在变量名或函数名前加上’__'两个下划线,那么这个函数或变量就会变成私有的了
insert image description here
定义私有变量,在外部无法访问
insert image description here
该进
insert image description here

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我今年 %d 岁了。" %(self.name,self.age))
 
# 实例化类
p = people('小明',8,30)
p.speak()
#输出
#小明 说: 我今年 8 岁了。

39.继承

派生类的定义格式:

class DerivedClassName(BaseClassName1):
    <statement-1>
    .
    .
    .
    <statement-N>
#BaseClassName(示例中的基类名)必须与派生类定义在一个作用域内。

insert image description here
如果子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法或属性
insert image description here
单继承举例(包括重写父类的方法)

class Parent():
      #定义普通属性
	name = ''
	age = 0
      #定义构造方法
	def __init__(self,n,a):
		self.name = n
		self.age = a
	def speak(self):
		print("%s说他今年%d岁了"%(self.name,self.age))
#单继承
class Child(Parent):
	sex = ''
	def __init__(self,n,a,s):
		Parent.__init__(self,n,a)#调用父类的构造函数
		self.sex = s
	def speak(self):
		print("%s说她今年%d岁了,并且她%s生"%(self.name,self.age,self.sex))
c = Child("小红",5,"女")
c.speak()
#输出
#小红说她今年5岁了,并且她女生
import random as r
class Fish:
        def __init__(self):
                self.x = r.randint(0,10)
                self.y = r.randint(0,10)
        def move(self):
                self.x -= 1
                print("我现在的位置是:",self.x,self.y)
class Goldfish(Fish):
        pass
class Carp(Fish):
        pass
class Shark(Fish):
        def __init__(self):
                self.hungry = True
        def eat(self):
                if self.hungry:
                        print("我要开始出东西啦")
                        self.hungry = False
                else:
                        print("太撑了,吃不下")

insert image description here
shark.move()报错是因为,定义子类Shark时的__init__(self)
与父类中的方法相同,父类中的__init__(self)被覆盖

该进方案1:
调用未绑定的父类方法

import random as r
class Fish:
        def __init__(self):
                self.x = r.randint(0,10)
                self.y = r.randint(0,10)
        def move(self):
                self.x -= 1
                print("我现在的位置是:",self.x,self.y)
class Goldfish(Fish):
        pass
class Carp(Fish):
        pass
class Shark(Fish):
        def __init__(self):
        		Fish.__init__(self)#调用未绑定的父类的方法,此时的self是子类Shark的实例对象
                self.hungry = True
        def eat(self):
                if self.hungry:
                        print("我要开始出东西啦")
                        self.hungry = False
                else:
                        print("太撑了,吃不下")

insert image description here
该进方案2:
使用super函数

import random as r
class Fish:
        def __init__(self):
                self.x = r.randint(0,10)
                self.y = r.randint(0,10)
        def move(self):
                self.x -= 1
                print("我现在的位置是:",self.x,self.y)
class Goldfish(Fish):
        pass
class Carp(Fish):
        pass
class Shark(Fish):
        def __init__(self):
                super().__init__()#不用给出基类的名字,自动找出基类对应的方法
                self.hungry = True
        def eat(self):
                if self.hungry:
                        print("我要开始出东西啦")
                        self.hungry = False
                else:
                        print("太撑了,吃不下")

insert image description here
super使用举例2

class A:
	def sub(self,x):
		y = x-2
		print(y)
class B(A):
	def sub(self,x):
		super().sub(x)
b = B()
b.sub(9)
#输出
#7

方法重写

class Parent:        # 定义父类
   def Method(self):
      print ('调用父类方法')
 
class Child(Parent): # 定义子类
   def Method(self):
      print ('调用子类方法')
 
c = Child()          # 子类实例
c.Method()         # 子类调用重写方法
super(Child,c).Method() #用子类对象调用父类已被覆盖的方法
#调用子类方法
#调用父类方法

多重继承

多继承类定义

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>
 #需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找父类中是否包含方法。

举例1
insert image description here
例2

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
 
#另一个类,多重继承之前的准备
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
 
#多重继承
class sample(speaker,student):
    a =''
    def __init__(self,n,a,w,g,t):
        student.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)
 
test = sample("Tim",25,80,4,"Python")
test.speak()   #方法名同,默认调用的是在括号中排前地父类的方法

40拾遗

组合

(把类的实例化放到新类里面,就把旧类组合进去了,就不用继承了)

class Turtle:
      def __init__(self,x):
            self.num = x
class Fish:
      def __init__(self,x):
            self.num = x
class Pool:
      def __init__(self,x,y):
            self.turtle = Turtle(x)
            self.fish = Fish(y)
      def print_num(self):
            print("水池里一共有%d只乌龟,%d条小鱼" %(self.turtle.num,self.fish.num))
#self.turtle是一个类

insert image description here

类、类对象和实例对象(00000)

类中定义的属性和方法是静态的

41.类与对象相关的BIF

issubclass(class,classinfo)

1.一个类被认为是自身的子类
2.如果 class 是 classinfo 的子类返回 True,否则返回 False。
insert image description here

isinstance(object,classinfo)

1.如果第一个参数不是对象,则永远返回False
2.如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False
insert image description here

hasattr(object,name)

hasattr() 函数用于判断对象是否包含对应的属性,如果对象有该属性返回 True,否则返回 False。
insert image description here

getattr(object, name[, default])
#object -- 对象。
#name -- 字符串,对象属性。
#default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

getattr() 函数用于返回一个对象属性值。
insert image description here

setattr(object, name, value)
#object -- 对象。
#name -- 字符串,对象属性。
#value -- 属性值。

setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的,如果属性不存在,则会创建该属性
insert image description here

delattr(object,name)
#object -- 对象。
#name -- 必须是对象的属性。

delattr 函数用于删除属性。

delattr(x, ‘foobar’) 相等于 del x.foobar。
insert image description here

class property([fget[, fset[, fdel[, doc]]]])
#fget -- 获取属性值的函数
#fset -- 设置属性值的函数
#fdel -- 删除属性值函数
#doc -- 属性描述信息

property() 函数的作用是在新式类中返回属性值。
insert image description here

42.构造与析构

init(self)

**情况一:**子类需要自动调用父类的方法:子类不重写__init__()方法,实例化子类后,会自动调用父类的__init__()的方法。

**情况二:**子类不需要自动调用父类的方法:子类重写__init__()方法,实例化子类后,将不会自动调用父类的__init__()的方法。

**情况三:**子类重写__init__()方法又需要调用父类的方法:使用super关键词:

super(子类,self).__init__(参数1,参数2....)
class Son(Father):
  def __init__(self, name):   
    super(Son, self).__init__(name)

init (self) The return value must be None (it needs to be used for initialization operations in general classes)
insert image description here
new (cls[,…]) The first method called when an object is instantiated, returns an object,
if inheritance cannot change the type and needs When modifying immutable types, you need to rewrite __new__(cls)
insert image description here
del (self)
insert image description here

43. Arithmetic operations 1

44. time time

1 The function time.time() is used to obtain the current timestamp

import time
ticks = time.time()
print(ticks)
#输出1600069594.4135377
#时间戳:每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。

2 Get the current time

import time
localtime = time.localtime(time.time())
print(localtime)
#输出time.struct_time(tm_year=2020, tm_mon=9, tm_mday=14, tm_hour=15, tm_min=48, tm_sec=50, tm_wday=0, tm_yday=258, tm_isdst=0)

3 Formatting dates
We can use the strftime method of the time module to format dates:

import time
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
#输出2020-09-14 16:00:33

Guess you like

Origin blog.csdn.net/qq_41238751/article/details/107878331