Simple , Open source , Portability , Explanatory 1, object-oriented , Extensibility , Rich library .
Slow running speed .
Cloud computing , Scientific computing and artificial intelligence ,web Development , Finance .
youtube、 douban 、 Know almost all python Development .
By default ,Python 3 Source file to UTF-8 code , All strings are unicode character string .
Encoding mode
ASCII code : The earliest code , common 128 character , English letters only , Numbers and symbols .
Unicode code : Unify the coding of all languages ,2 byte .
UTF-8 code : To solve the problem Unicode The waste of memory and storage space Unicode Encoding into variable length encoding UTF-8 code .UTF-8 To encode common English letters into 1 Bytes , Chinese characters are usually 3 Bytes ; For example, the transmitted text contains a large amount of English , use UTF-8 Coding saves space .
The common character coding mode of computer system
Unified use in computer memory Unicode code , When it is saved to the hard disk or needs to be transferred, it is converted to UTF-8 code .
When editing with Notepad , Read from file UTF-8 The characters are converted to Unicode Into memory , Save it before Unicode Convert to UTF-8; While browsing the web , The server dynamically generates Unicode Content to UTF-8 Then transfer to browser , If the web source code is similar
<meta charset="UTF-8" />
The information of indicates that the web page is marked with UTF-8 code .
from Letter 、 Numbers and underscores form , The first character must be a letter or underscore in the alphabet ; stay Python 3 in , It can be used Chinese as variable name , Not ASCII Identifiers also allow .
import keyword
keyword.kwlist # Output all keywords of the current version
Single line comment with #
start , Multi line comments can use multiple #
Number or '''
and ""
.
Use indents to represent code blocks , Statements in the same code block must contain the same number of indented spaces , You don't need braces {}
.
\\
To implement multiline statements ; stay [], {}, or () Multiple lines in , No need to use backslash \\
;
Division input("")
# default input() by str Format , If you use mathematics , You need to convert the format , Such as :
int(input())
print()
# default print() It's a new line , You need to add... At the end of the variable without newline end="":
print( x, end=" " )
Python The variables in the No declaration required ; Each variable must be before use Assignment must be made. ( Can be null ), The variable will not be created until it is assigned a value .
stay Python in , Variable has no type , What we say " type " Is the type of object in variable memory . A variable can be assigned to different types of objects .
Six standard data types :
str = 'python 3.8'
tuple = ('python', 3.8)
list = ['python', 3.8]
dict = {
1: 'python', 'key2': 3.8}
set = {
'python', 3.8}
# Index slice :
list=[1.2,'1',['a',1],(1,2),{
'name':'zhangsan'}
print(test[2]) # Indexes
print(test[0:3]) # section , Left closed right away
['a',1]
[1.2,'1',['a',1]]
list=[1.2,'1',['a',1],(1,2),{
'name':'zhangsan'}
# increase :
list.append('list') # Add at the end
list.extend(['list',10,'hello']) # Add more , Use list []
list.insert(0,'list') # Index insertion
# modify
list[1]='list'
# Delete
list.remove(1.2) # Output according to the element
list.pop() # The index defaults to , Delete the last element by default
del list[0] # Delete... According to index
list.clear() # Remove all elements
dict['key1']
; The keys of the dictionary must be immutable , You can use numbers 、 String or tuple , It can't be a list .int、float、bool、complex( The plural )
Shield escape : With r or R Before string quotation marks ;
Three quotes allow a string to span multiple lines .
%
The operator :
print(' pi is approximately %5.3f' % math.pi)
>>>pi is approximately 3.142
print(f' pi is approximately {
math.pi:.3f}')
>>>pi is approximately 3.142
print(' the {} who say "{}!"'.format('knights', 'Ni'))
>>>the knights who say "Ni!"
Built in type() Function can be used to query the object type of variable :
print(type(a))
<class 'int'>
Or use isinstance To judge :
>>>isinstance(a, int)
>>>True
isinstance and type The difference is that :type() A subclass is not considered a superclass type , and isinstance() Meeting .
1.if sentence
if...elif...elif...
Instead of switch...case...
sentence .
2.while sentence
3.for sentence for...in...
Iterate over any sequence , When traversing a sequence of numbers, use range() sentence :
for i in range(0, 10, 1) # Stepping
4.break and continue sentence
break Used to jump out of the nearest for or while loop ,continue Indicates to continue the next iteration in the loop .
5.else Clause
stay if,while and for Can be used in ;
Cyclic quilt break and continue Do not run on abort else Clause .
6.pass sentence
placeholder .
- Default parameters
When you call a function , If no parameters are passed , Then the default parameters .- Key parameters
Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared .- Indefinite length parameter
With an asterisk*
Will be imported as tuples , Store all unnamed variable parameters , Add two asterisks**
The parameters of are imported as dictionaries .- Anonymous functions
Use lambda To create anonymous functions , That is, no longer use def Statement to define functions .
The use of modules allows authors of different modules not to worry about having the same global variable names as each other ; A package is a way of using “ Module name with dot ” To construct the Python Method of module namespace , The use of dotted module names allows authors of multi module software packages not to worry about the same module names as each other .
__name__ attribute
__name__
attribute : Each module has one __name__
attribute , When the value is __name__
when , Indicates that the module itself is running , Otherwise it's introduced . usage :if __name__ == '__main__':
from fibo import fib, fib2
when ,fibo Undefined . The definition of a class contains the definition of properties and methods , The methods defined by a class generally contain constructor __init__()
; Variables defined in methods , Class that only works on the current instance .
__private_attrs
: Start with two underscores , Declare the property private , Can't be used outside of the class or accessed directly . When used in methods within a class :self.__private_attrs
.__private_method
: Start with two underscores , Declare the method private , Can only be called inside a class , Cannot call... Outside of a class :self.__private_methods
. Class instantiation will automatically call the constructor __init__()
, After class instantiation, you can reference properties and methods .
Subclass ( Derived class DerivedClassName) Will inherit the parent class ( Base class BaseClassName) Properties and methods of .
class people:
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s say : I %d year ." %(self.name,self.age))
# Single inheritance example
class student(people):
grade = ''
def __init__(self, n, a, w, g):
# Call the constructor of the parent class
people.__init__(self, n, a, w)
self.grade = g
# Overrides the method of the parent class
def speak(self):
print("%s say : I %d Year old , reading %d grade " % (self.name, self.age, self.grade))
class sample(speaker,student):
super(Class, self).xxx
You can call the parent class ( Superclass ) Methods ,super()
Used to solve multiple inheritance problems , It's OK to call the parent class method directly with the class name when using single inheritance , But if you use multiple inheritance , There's a search order involved 、 Repeated calls, etc .Python 3 It can be used
super().xxx
In the form of .
__call__()
Method Object name ()
In the form of .1. The catching :
try...except...else...finally
Abnormal execution occurs except:
After the code , No exception execution occurred else:
After ,finally
It will execute whether there is an exception or not .
2. Throw an exception ( Take the initiative ):
raise sentence .
3. User defined exception :
Have your own exceptions by creating a new exception class . Exception classes inherit from Exception class , Can inherit directly , Or indirectly .
with open("/tmp/foo.txt") as file:
data = file.read()
Explanatory :Python A program written in C language does not need to be compiled into binary , You can run the program directly from the source code . Inside the computer ,python The interpreter converts the source code into an intermediate form called bytecode , Then translate it into machine language and run . ︎