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

Python learning

編輯:Python

One 、Python summary

1. summary
Python It's famous “ Uncle GUI ”Guido van Rossum stay 1989 Written during Christmas in .
Python Provides us with a very complete basic code base , Network coverage 、 file 、GUI、 database 、 A lot of content such as text , It's figuratively called “ Built in battery ”. use Python Development , Many functions don't have to be written from scratch , Just use the ready-made ones .
Uncle GUI, here you are Python The location is ” grace “、” clear “、” Simple “, therefore Python The program always looks easy to understand , Beginner study Python, Not only is it easy to get started , And in the future , You can write very complex programs .

2.Python application
a. Website background development -PythonWeb
b. Daily gadgets Ops scripts
c. Encapsulate packages developed in other languages Convenient to call - Glue language
d. The crawler development -python Reptiles
e. Scientific Computing AI The field has unique advantages -python Is an artificial intelligence language

3.Python
advantage :
Easy to learn
Perfect language features
Natural open source
Rich community support
shortcoming :
slow
python It's an interpretive language , The code you write is the execution code , stay python When the program is executed , from python Interpreter , Read and interpret , While executing , Low efficiency .
So when developing high-performance programs , Basically do not consider python. But in the case of ordinary applications that do not pursue extreme efficiency ,python The disadvantage of being slow is not obvious , and python Simple The advantage of efficient development capability is obvious , So it is widely used
The code can't be encrypted
because python It's an interpretive language , The code you write is the execution code , So it will python The process of program release is the process of source code release , Code can not achieve the effect of confidentiality , But it is this characteristic that determines python From the language level, it is naturally open source , This is also python One of the reasons for the rapid development of the community .

Two 、Python The installation configuration uses

1.Python Installation configuration
bearing python Official website , download python Installation package
https://www.python.org/downloads/
python It is currently divided into two major versions , Not compatible with each other
2.x.x
3.x.x
Double click installation
python-2.7.13.amd64.msi
Set the environment variable
take python The installation location is configured to PATH Under environment variable .

2.Python How to use
a.shell Command mode
Execute commands interactively at the command line
stay cmd By command python Order to enter python Command line , Write code interactively to process data

b. take python Uninstall file
You can write the code in .py In file , Re pass python Command execution file
c. Use IDE Tool development python
①pycharm
Officially recommended python development tool
②eclipse install python Developing a plug-in
send elipse Have the ability to develop python The ability of

3、 ... and 、Python grammar

1. Grammatical details
a. code
python2 Parser python The default file is iso8859-1.python3 Mode use utf-8
If python If the code of the document itself is inconsistent with the above code, there will be garbled code
At this time, the following comments can be used in the file to inform the interpreter of the encoding used when parsing the current file , If the two codes are consistent, it can be solved
The statement :

b. Sentence making
python Usually one line is one statement , Semicolon identification is not required
If you write multiple statements on one line , You need to use semicolon segmentation to prevent ambiguity
c. Indent
python Curly braces are not used as the identity of the scope in , Instead, tabs are used to identify the scope

d. notes
python Use # As a single line comment Use three single quotes or Three double quotes as a multiline comment

e. References and constant variables
python There are no declared referenced keywords , To write the name of a reference directly is to declare a reference .
python There is no distinction between data types , That is, a reference can be pointed to different types of data successively .
python Small and medium-sized references identify variables An uppercase reference represents a constant , When you need to pay attention , Here constants are just a convention , Ask future users not to modify , But it's essentially a variable , If you really modify it, you can modify it successfully .

2. identifier
stay python in , All identifiers can include English 、 Numbers and underscores (_), But don't start with a number .
python Identifiers in are case sensitive .
stay python Middle underline _ It has a special meaning
1) Start with a single underline _foo Representatives of cannot directly access class properties , It needs to be accessed through the interface provided by the class , Out-of-service from xxx import * visit :
2) Beginning with a double sliding line __foo Represents a private member of a class
3) Beginning and ending with double underscores __foo__ representative python A special way of marking , Such as __init__() Represents the construction method of a class
3. data type
python There is no data type when referencing in , But the data itself is of different types
a. character string
You can use single quotes , Double or triple quotation marks to declare a string literal
There is no difference between single quotation marks and double quotation marks
A string declared in three quotation marks can contain any character , These characters are treated directly as the contents of the string Thus eliminating the process of escape
python Can also be used in r or R Decorate before the string literal , The surface current string ignores the escape and directly uses the original value

python Strings provide a large number of operation methods :

b. Boolean
A Boolean direct has only two values
True False
c. The number
python Represents the type of data in , There are four kinds of direct values :
integer
It's usually called an integer or an integer , It's a positive or negative integer , Without decimal point .
Long integer
An integer of infinite size , The last upper or lower case of an integer L.
floating-point
Floating point type consists of integer part and decimal part , Floating point types can also be represented by scientific notation (2.5e2=2.5 x 10^2=250)
The plural
A plural number consists of real and imaginary parts , It can be used a+bj, perhaps complex(a,b) Express , Real part of negative number a Deficiency part of harmony b It's all floating point .
Numeric types provide a number of methods of operation :



d. Null value
Be similar to java Medium null, No value , There is only one direct quantity
None
x=Node(JAVA:Object = null)

Four 、 Operator

a. Arithmetic operator

b. Compare ( Relationship ) Operator

c. Assignment operator

d. An operator

e. Logical operators

f. member operator

g. Identity operator

h. Operator precedence

5、 ... and 、 sentence

a. Conditional statements
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-QuuaFPRe-1654440257030)( https://img-blog.csdnimg.cn/c72654b42d9f4c709984806cefad4c21.png)]

b. Loop statement while

c. Loop statement for

Add :

6、 ... and 、 important API: Collection classes

1. list -list
It can be used to store Content of the variable Variable length The types can be different The data structure of ordered data
Be similar to java Of List
Basic use of lists :

Other functions of the list :

2. Tuples - tuple
A list of tuples :
Tuples themselves are immutable data types , There are no additions, deletions and changes
② Any data type can be stored in the tuple
The basic use of tuples :

Other functions of tuples

3.Set - Involve set
Do not modify the Do not repeat disorder The types can be different A list of
Be similar to java Medium Set
set The basic usage of :

4. Dictionaries - dict
Store data of key value pair type Key is not repeatable disorder
Be similar to java Of Map
dict The basic usage of :

dict Other methods :

7、 ... and 、 function

1. Defined function
a. Definition of ordinary function
adopt def Keywords define functions , A list of arguments wrapped in function names and parentheses , Followed by a colon , Write the function body after it .
The first line of the function body , It can be a string directly , This string does not affect the contents of the function body , It is equivalent to the documentation of the method , Used to describe the function of a function , You can view it later .
Function contents need to be indented .
adopt return Keyword returns... Inside a function , And can optionally return a return value , If return There is no explicit return value after , The default return is a None.

## Defined function 
def sumx(n1,n2):
" Sum function of two numbers "
return n1+n2

b. Function direct quantity defines function
adopt lambda Expression to declare a function ,lambda Keyword followed by parameter list , Followed by a colon , Then the body of the function , The body of a function declared in this way can only be an expression , If the function body has multiple statements , Cannot be defined in this way .

## Function direct quantity defines function 
sumx = lambda arg1,arg2:arg1+arg2
print(sumx(2,3))

2. Function call
You can call a function by passing in the parameter value after the function name and the parentheses
During the call of function , You can also specify the formal parameter to which the argument should be assigned in the argument list , Thus, the order of the argument list can be different from that of the formal parameter list

## Function call 
def sumx3(n1,n2,n3):
return n1+n2+n3;
print sumx3(1,2,3)
print sumx3(n3=3,n2=2,n1=1)

3. Default parameters
In the process of defining a function , You can specify default values for all or part of the function parameters , You can selectively not pass in these parameters in the process of calling the function , Then these parameters execute the function with default values .

## Default parameters 
def sumx4(n1,n2=10):
return n1 + n2;
print sumx4(2,3)
print sumx4(2)

4. Indefinite length parameter
Be similar to java Variable parameters in ,python Functions in can also have indefinite length arguments , When calling again in the future, you can pass 0 Two or more parameters , The variable length parameter can be used inside the function as an array .
You can add... Before the formal parameter name * Number , Set the parameter as variable length parameter .
In a function , There can only be one variable length parameter at most , And must appear at the last place in the function parameter list .

## Indefinite length parameter 
def sumx5(*ns):
s = 0;
for x in ns:
s += x;
return s;
print sumx5(2,3)
print sumx5(2,3,4)
print sumx5(2,3,4,5)

5. Functions are first class citizens
stay python First class citizen of the function in , Have complete ability , Property can do any function .
a. Assign to reference

## Functions are first class citizens 
def sumx6(n1,n2):
return n1 +n2;
print sumx6(2,3)
sumx7 = sumx6
print sumx7(2,3)
sumx6 = None
sumx7 = None

b. As a member of a class

class Person:
name = "zs";
age = 18;
def eat(self):
print " eat .."
def say(self):
print " say .."

c. As a local member

def eat(food):
def cook(food):
return " Cooked "+food;
print " eat "+cook(food)
eat(" Mutton string ")

d. The higher-order function is used as the parameter of the method

def eatx(food,cookFunc):
food2 = cookFunc(food)
print " eat "+food2
def cookYRC(food):
return " Baking tray "+food;
eatx(" Mutton string ",cookYRC)
eatx(" Hot Pot, Mongolian Style ",lambda food:" Cooked "+food)

e. Higher order function as method return value

def lookupCP(cai):
if " Mutton string " == cai:
def cookYRC(food):
return " toast "+food;
return cookYRC;
elif " Hot Pot, Mongolian Style " == cai:
return lambda food:" Cooked "+food;
else:
return lambda food:" Cooked "+food;
cookFunc = lookupCP(" Mutton string ")
print cookFunc(" Mutton string ")
cookFunc = lookupCP(" Hot Pot, Mongolian Style ")
print cookFunc(" Mutton string ")

modular 、 package

1. The concept of modules
Python modular (Module), It's a Python file . With .py ending , Which includes Python Object definition and Python Sentence, etc .
Simply speaking , One Python The document is a python modular .
Python It is a structured organization of projects in modules .
Assign the relevant code to a module to make your code better , Easier to understand .
Modules can define functions , Classes and variables , Modules can also contain executable code .
2. Introduce modules
If the content defined in other modules is used in one module , You need to introduce this module into the current module . This process is similar to java The process of guiding packets in , stay Python It is called the introduction module .
a. Introduction of modules 1:

#import module[module2[...moduleN]
import math;
print math.floor(3.14)
import Demo01;
print Demo01.sumx(2,3)

b. Introduction of modules 2:

#from modname import name1[name2[...nameN]]
from math import *
print floor(3.14)
from Demo01 import sumx;
print sumx(2,3)

Search path :
When you import a module ,Python The search order of the parser for the module location is :
1) Current directory
2) If not in the current directory ,Python Search in shell Variable PYTHONPATH Every directory under .
3) If you can't find ,Python You'll see the default path .UNIX Next , The default path 1 is /usr/local/lib/python/.Windows Usually c:\…\system32 Under the table of contents

3. package
A package is a hierarchical file directory structure , Used to organize program structure .( Function and java equally )
Simply put, a package is a folder .
But in python Not all folders in are packages , A folder must have a folder named __init__.py Files are recognized as packages .
__init __.py On the one hand, a document is an identification , Identify that the current folder is a package , On the other hand , The code in this file will be python The package is used and executed for the first time .

important API - IO

1. Print

print("abc")

2. Keyboard reading
a.raw_input Function to read the keyboard
Reading in this way , Will return the input as a string
str=raw_input(“ Please enter :”);
b.input Function to read the keyboard
Reading in this way , The input will be executed as an expression , Returns the result of the expression execution

str = input(" Please enter : ")

3. Read and write files
open Function operation file :

file Object properties

4. system operation

Exception mechanism


2. Capture exception
When an exception is thrown , You can catch exceptions using the following methods :

3. Throw an exception manually
adopt raise keyword , You can throw exceptions manually

raise [Exception[,args[,traceback]]]

4. Custom exception
You can write a class inheritance Exception To develop a custom exception

object-oriented

1. Create a class
Use class Keyword to create a class ,class Followed by the name of the class and ending with a colon , Heel like body .
You can write a string in the first line of the class body , As a document declaration of this class , This document declaration can be made through ClassName.__doc__ see :
The body of a class can contain member attributes Member method Construction method, etc

class Person:
" Class representing people "
name = ""
age = "bj"
def __init__(self,name,age):#self amount to java Of this
self.name = name;
self.age = age;
def eat(self):
print(self.name + " eat ....")
def say(self):
print(self.name+ " say ...")
print Person.__doc__
p = Person("zs",18)
print p.name
print p.age
p.eat()
p.say()

2. Create properties
python Class can contain member attributes . When creating objects of this class , Objects will have this attribute by default .
3. Member method
python Methods in a class differ from other methods in that , There must be a method called self Parameters of , This self Represents the current object itself , amount to java Medium this
4. Construction method
python Classes in can specify constructors . stay python Class is defined as __init__ Methods , Namely python Construction method of .
5. Create objects
python There is no new keyword , You can create objects by using the class name directly
6. Add attributes and methods for deleting objects
stay python in , The relationship between class and object is not a strong relationship , Class is just a template for creating objects , Once the object is created , An object is an individual , You can add or delete attributes and methods by yourself .
Be careful , The delete operation can only delete the attributes and methods added the day after tomorrow , Properties and methods in a class cannot be deleted
in addition , You can add a delete attribute method after the object is created , It means that even objects created by the same class , It can also be very different .

p1 = Person("ls",20)
# Attribute added 
p1.addr = "bj"
# Increase method 
p1.sumx = lambda n1,n2:n1+n2;
print p1.addr
print p1.sumx(2,3)
# Delete attribute 
del p1.addr
# Delete method 
del p1.sumx

7. Class
python Class automatically contains several built-in properties , These built-in properties often have specific functions

#__dict__: Attributes of a class ( Include a dictionary , Consists of data properties of a class )
#__doc__ Document string for class 
#__name__ Class name or module name 
#__module__: Module of class definition 
#__bases__: All parent elements of a class ( Contains a tuple of all parent classes )
print Person.__doc__
print Person.__dict__
print Person.__module__
print Person.__name__

Case study :
If the current module is the entry of the program , The module name will be changed to __main__, If not, the module name is equal to the file name .
therefore , Such code is usually written in modules , So that the module can be directly executed and import Import is to perform different logic

if __name__=='__main__':
The logic that goes when a module is directly executed
else:
When the module is import The logic executed when importing

8. Class encapsulation - Access control
python The properties and methods of classes in can directly control access permissions , The control method is :
① If the property or method name begins with a single underscore , Means that the property or method is a protected member , Can only be accessed inside a class or subclass , But this is just an agreement , There is no such restriction at the grammatical level .
② If the property or method name begins with a double underscore , Is a private member , Can only be accessed inside a class , The outside world cannot use , This is a python Part of grammar .

class Person :
" Class representing people "
__name = "zs"
def __say(self):
print(" say ...")
p = Person
print(p.__name)# Property privatization , I can't visit , Wrong interview 
p.__say()# Method privatization , I can't visit , Wrong interview 

9. Class inheritance
python Class supports inheritance .python Support for multiple inheritance .
The grammar of inheritance :

 class subClass(superClass,[...]):
The class body

Subclasses do not automatically call the constructor of the parent class when constructing , if necessary , You should explicitly call the parent class constructor in the constructor of the child class .
When a parent method is called in a subclass , You need to call... Through the parent class name .
If multiple inheritance , Multiple parent classes have methods with the same name , Which one to inherit depends on the inheritance order of the parent class , The higher the priority in the inheritance declaration, the higher the priority .
In the subclass, if you don't like the methods of the parent class , Rewriting operations can be performed , Declare a method in a subclass that has the same name and parameters as the parent class , Do it yourself .

class Person :
" Class representing people "
name = ""
age = 20
def __init__(self,name,age):#self amount to java Of this
self.name = name;
self.age = age;
def eat(self):
print(self.name + " eat ....")
def say(self):
print(self.name+ " say ...")
class Coder:
def code(self):
print(" Write code ..")
def run(self):
print(" come on. , Drag racing ..")
class Driver:
def driver(self):
print(" Driving a car ..")
class Teacher(Person,Coder,Driver):
def teach(self):
print self.name + " teach .."
t = Teacher("ww",33)
t.teach()
t.driver()
t.code()
t.run()

10. Class polymorphism
python Reference in has no type , References can be equal to completely different types of data , Naturally, there is no concept of polymorphism .
11. Basic method overrides
python There are many basic methods in the classes in , These methods provide class specific functionality , You can override the implementation of these specific functions by overriding these methods .

__init__(self[,args...]): ( amount to java Construction method of )
Construction method
__del__(self)
destructor , What to do after deleting an object
__str__(self)
Used to convert values into a form suitable for human reading ( amount to java Medium toString Method )
__cmp__(self,x)
Compare the two objects ( amount to java Of compareTo Method )

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