relearn python

language features

First of all, python is an easy-to-learn language with rich third-party libraries, which are widely used in crawlers, automated testing, data analysis, AI and other fields

type of data

pyhton standard types

  • Numbers
  • String (string)
  • List (list)
  • Tuple
  • Dictionary

Python supports four different data types

  • int (signed integer)
  • long (long integer, can also represent octal and hexadecimal)
  • float (floating point type)
  • complex (plural)
text type: str
Numeric type: int, float, complex
sequence type: list, tuple, range
Mapping type: dict
collection type: set, frozenset
Boolean type: bool
Binary type: bytes, bytearray, memoryview

variable declaration

x = "Hello World" 
x = 29
x = 29.5
x = 1j
x = ["apple", "banana", "cherry"]
x = ("apple", "banana", "cherry")
x = range(6)
x = {"name" : "Bill", "age" : 63}
x = {"apple", "banana", "cherry"}
x = True

Conditions and Loops

num = 80
if num > 80:
  print("优")
elif num > 60 and num < 80:
  print("良")
else
  print("差")
  
if ( var  == 100 ) : print "变量 var 的值为100" 

cycle

num = 0
while(num < 10):
  print(i)
  num++
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print ('当前水果: %s'% fruit)

Common Data Containers

//list
x = ["apple", "banana", "cherry"]
//元组
x = ("apple", "banana", "cherry")
x = range(6)
//字典
x = {
    
    "name" : "Bill", "age" : 63}

function declaration

def add(a, b):
  return a+b
//箭头函数声明  
sum = lambda arg1, arg2: arg1 + arg2

#可写函数说明
def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print "Name: ", name
   print "Age ", age
   return
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print "输出: "
   print arg1
   for var in vartuple:
      print var
   return

object oriented

class Employee:
   '所有员工的基类'
   empCount = 0
 
   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount
 
   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary
      
      
"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)

inherit

class Parent:        # 定义父类
   parentAttr = 100
   def __init__(self):
      print "调用父类构造函数"
 
   def parentMethod(self):
      print '调用父类方法'
 
   def setAttr(self, attr):
      Parent.parentAttr = attr
 
   def getAttr(self):
      print "父类属性 :", Parent.parentAttr
 
class Child(Parent): # 定义子类
   def __init__(self):
      print "调用子类构造方法"
 
   def childMethod(self):
      print '调用子类方法'
 
c = Child()          # 实例化子类
c.childMethod()      # 调用子类的方法
c.parentMethod()     # 调用父类方法
c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
c.getAttr()          # 再次调用父类的方法 - 获取属性值

exception handling

try:
    正常逻辑
except Exception,err:
    触发自定义异常    
else:
    其余代码
    
try:
<语句>
finally:
<语句>    #退出try时总会执行
raise

concurrency

# 为线程定义一个函数
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )
 
# 创建两个线程
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"
 
while 1:
   pass
class myThread (threading.Thread):   #继承父类threading.Thread
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 
        print "Starting " + self.name
        print_time(self.name, self.counter, 5)
        print "Exiting " + self.name

Modular words

Python Modules module

Modules are files that contain Python definitions and statements. The file name with a .py suffix is ​​the module name.

Within a module, the name of the module can __name__be represented (string).

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

Here fibo.py is a module, and fib and fib2 are functions in the fibo module.

import module

There are three ways to import modules

1. Import the entire module

#import module_name
import fibo

2. Import module-specific functions

#from module_name import function_name
from fibo import fib, fib2

fib(10)

3. Import all functions of the module

#from module_name import *
from fibo import *

fib(20)

You can also give an alias

# import module as m
import numpy as np

a = np.arange(100)

Run modules individually

If we want to test the module separately, we can add the following code to the module, which can be used as both a script and an importable module :

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

Python Packages

The Packages package can be understood as a container for a set of modules , and the namespace is constructed in the way of Package.Module

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              ...

  • init.py must have this file in order for Python to treat the directory containing the file as a package (Package). init.py can be an empty file, or it can execute the initialization code of the package or set the __all__ variable.

  • formats/ , effects/ , filters/ are subpackages (Subpackage), and each subpackage also has a __init__.py file.

  • Files such as echo.py are modules in subpackages (Module), which may contain functions, classes, or variables

Referencing a module in a package

from sound.effects import echo

echo.echofilter(input, output, delay=0.7, atten=4)

Reference to a function or variable in a submodule in a package

from sound.effects.echo import echofilter

echofilter(input, output, delay=0.7, atten=4)

Reference Packages and Modules Using Relative Paths

from . import echo
from .. import formats
from ..filters import equalizer

python common library

Data analysis: Numpy, pandas

web:django

Reptile: urllib, urllib2, requests

Reference: https://blog.csdn.net/Bit_Coders/article/details/119318000

Guess you like

Origin blog.csdn.net/lin819747263/article/details/128762655