Python

Manual

FAQ

  • https://blog.csdn.net/weixin_42397937/article/details/123325716
  • requests 文件上传等 https://blog.csdn.net/wl18271672781/article/details/125265473
  • Flask https://blog.csdn.net/qq575792372/article/details/99951608/
  • https://www.orcode.com/question/846787_k5266f.html
  • Flask https://blog.csdn.net/weixin_44239541/article/details/89390139
  • Flask 跨域 https://www.bbsmax.com/A/nAJv1j8nzr/
  • base64转图片 https://blog.csdn.net/weixin_46081055/article/details/120107358

B 站的几个视频

图片处理

Pillow

OpenCV

  • https://www.bilibili.com/video/BV1Fd4y1G75E
  • https://baijiahao.baidu.com/s?id=1751359493905103975
  • https://www.likecs.com/show-204182867.html
  • https://www.jb51.net/article/244229.htm
  • https://blog.csdn.net/weixin_43483381/article/details/122551027
  • https://blog.csdn.net/weixin_43561913/article/details/128836493
  • https://www.cnblogs.com/zwj365589/p/11817444.html

文件类型

  • https://www.bbsmax.com/A/ZOJPVOEKdv/

Excel

下面是基础部分

0 概览

pip

iPython

pip install ipython
  • 不用分号
  • // 整除
  • ** 幂 pow()
  • input() print()
  • raw_input() Python 2 eval(raw_input('...'))
  • from math import sqrt
  • str() repr() `x`(v2)
  • 三个引号
  • 原始字符串 r
  • Unicode u

1 序列 sequence

1.1 列表 list

greeting = 'Hello'
greeting[0] # H
greeting[-1] # o
endings = ['st','nd','rd'] + 17 * ['th']
  • 分片
  • 步长
  • 成员资格 in
  • len min max
  • list join 函数
  • del 语句
  • 分片赋值
  • append count extend index insert(3,'four') pop() 方法
  • remove 改变列表,无返回值
  • reverse 改变列表,无返回值
  • sort sorted sort(cmp) sort(key=len) sort(reverse=True)
x = [4,6,2,1,7,9]
y = x[:]
y.sort()
y = sorted(x)

1.2 元组

  • (42,)
  • tuple 函数
  • 分片
  1. 作为键使用
  2. 内建函数和方法的返回值
x = 1,2,3
x[1] # 2

2 字符串

  • 所有序列操作对字符串适用

  • ==字符串格式化==

  • 字符串常量

string.digits
string.letters
string.loercase
string.printable
string.punctuation
string.uppercase

2.1 字符串方法

  • find
  • ==rfind index rindex count startswith endswith==
title = "Monty Python's Flying Circus"
title.find('Python')
# 6

# 提供起始点和结束点
title.find('Python', 1, 5)
  • join 'str'.join(seq)
  • lower 'STR'.lower()
  • ==islower capitalize swapcase title istitle upper isupper==
  • string.capwords('str str')
  • replace 'str'.replace('s','ss')
  • ==expandtabs==
  • split
  • ==rsplit splitlines==
  • strip 'str!!++'.strip('+!')
  • ==lstrip rstrip==
  • ==translate 处理单个字符==
  • ==string.maketrans('str','rts')==

Unicode 字符串

buffer 对象

xrange 对象

3 字典

  • dict
  • 格式化

3.1 字典方法

  • clear() 无返回值,同时清空关联字典
  • copy() 浅复制
x = {'username':'admin', 'machines':['foo', 'bar', 'baz']}
y = x.copy()
y['username'] = 'mlh'
y['machines'].remove('bar')
y
# {'username':'mlh', 'machines':['foo', 'baz']}
x
# {'username':'admin', 'machines':['foo', 'baz']}
  • deepcopy()
from copy import deepcopy
y = deepcopy(x)
  • fromkeys()
dict.fromkeys(['name','age'],'strForValue')
  • get d.get('get','ReturnValue') 访问不存在的键值不会报错(返回 None 或自定义)
  • setdefault() 类似 get() 如果键值不存在会更新
  • has_key() Python 2
  • items() iteritems()
d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
it = d.iteritems()
list(it)
  • keys() iterkeys() values() itervalues()
  • pop d.pop('key')
  • popitem() 随机移除
  • update() 如有重复则覆盖

4 语句

  • print
  • import

import somemodule

from somemodule import somefunction

from somemodule import somefunction, anotherfunction, yetanotherfunction

from somemodule import *

# module 别名
import math as foobar 

# 函数别名
from math import sqrt as foobar

4.1 赋值

  • 序列解包
x, y, z = 1, 2, 3
x, y = y, x

values = 1, 2, 3
x, y, z = values

  • 链式赋值
  • 增量赋值

5 语句

假 False None 0 '' () [] {}

  • bool()

5.1 if

if condition1:
    print('1')
elif condition2:
    print('2')
else:
    print('3')
  • is 同一性运算符
x = y = [1, 2, 3]
z = [1, 2, 3]
x == y
# True
x == z
# True
x is y
# True
x is z
# False
  • 短路逻辑 惰性求值
  • 断言 assert
age = -1
assert 0 < age < 10, 'AssertionError Description'

5.2 while && for

  • zip 返回元组列表
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
zip(names, ages)
for name, age in zip(names, ages):
    print(name, 'is', age, 'years old.')
  • ==enumerate==
for index, string in enumerate(strings):
    if 'xxx' in string:
        strings[index] = '[censored]'
  • sorted() list()
  • while True/break
  • for else 没有调用 break 的时候执行 else

5.3 列表推导式

[x*x for x in range(10)]
[x*x for x in range(10) if x % 3 == 0]
[(x, y) for x in range(3) for y in range(3)]

girls = ['alice', 'bernice', 'clarice']
boys = ['chris', 'arnold', 'bob']
[b+'+'+g for b in boys for g in girls if b[0] == g[0]]

# 更优方案
letterGirls = {}
for girl in girls:
    letterGirls.setdefault(girl[0], []).append(girl)
print([b+'+'+g for b in boys for g in letterGirls[b[0]]])

5.4 其它

  • pass 空代码块占位
  • del
  • exec eval
# 会出错的代码
from match import sqrt
exec 'sqrt = 1'
sqrt(4)

# 使用命名空间 <scope>
from math import sqrt
scope = {}
exec 'sqrt = 1' in scope
scope['sqrt']

6 函数

6.1 定义

  • callable Python 2 hasattr(func, __call__)
  • def
def hello(name):
    '这里是文档字符串'  # hello.__doc__
    return 'Hello, ' + name + '!'

6.2 参数

names = ['Mr. Gumby', 'Mrs. Thing']
change(names[:])  # 避免影响原值
  • 改变参数
  • 关键字参数和默认值
  • 收集参数 def print_params(*params1, **params2)
  • 参数收集的逆过程(调用时使用星号)

6.3 作用域

  • 作用域 vars() locals() globals()
  • 函数内重绑定 global nolocal
  • 闭包

6.4 递归

  • 三个经典实例
# 阶乘 改造前
def factorial(n):
    result = n
    for i in range(1,n):
        result *= i
    return result
    
# 阶乘 改造后
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

# 幂 改造前
def power(x, n):
    result = 1
    for i in range(n):
        result *= x
    return result

# 幂 改造后
def power(x, n):
    if n == 1:
        return x
    else:
        return x * power(n-1)

# 二分法查找 改造前


# 二分法查找 改造后

7 对象

7.1 创建对象

__metaclass__ = type # 使用新式类 Python 3 默认使用新式类

class Person:

    def setName(self, name):
        self.name = name

    def getName(self, name):
        return self.name

    def greet(self):
        print('Hello, world! I\'m $s.' % self.name)

foo = Person()

foo.greet() # Person.greet(foo)

  • 私有属性
class Secretive:
    def __inaccessible(self):
        print('Bet you can see me...')
    
    def accessible(self):
        print('The secret message is:')
        self.__inaccessible()

# 依旧可以读取
s = Secretive()
s._Secretive.__inaccessible()

7.2 继承

class Calculator:
    def calculate(self, expression):
        self.value = eval(expression)
    
class Talker:
    def talk(self):
        print('Hi, my value is', self.value)

# 继承多个超类
class TalkingCalculator(Calculator, Talker):
    pass

  • 继承检查
issubclass(SPAMFilter, Filter)

SPAMFilter.__bases__

isinstance(s, SPAMFilter)

s.__class__

type(s) # 新式类
  • 接口和内省
hasattr(tc, 'talk')

callable(getattr(tc, 'talk', None)) # Python 2

hasattr(x, '__call__') # Python 3

setattr(tc, 'name', 'Mr. Gumby')

7.3 构造方法

__init__

# 继承超类的构造方法
1. 超类.__init__(self)
2. super(子类, self).__init__()

7.4 ==property==

7.5 ==静态方法和类成员方法==

7.6 __setattr__

  • __getattribute__(self, name) 新式类
  • __getattr__(self, name) 没有相应特性时调用
  • __setattr__(self, name, value)
  • __delattr__(self, name)

==迭代器==

8 异常

raise Exception('hyperdrive overload')
import exceptions
dir(exceptions)
  • 捕获异常
try:
    pass
except (ZeroDivisionError, TypeError) as e:
    pass
while True:
    try:
        x = input('input the first number:')
        y = input('input the second number:')
        value = x/y
        print('x/y is', value)
    except Exception as e:
        print('Invalid input:', e)
        print('Please try again')
    else:
        break
  • finally

9 模块

  • 导入时执行
import module
from module import x
from module.x.x import x as rename
from module.x.x import *
import sys
sys.path.append('c:/python')
  • 重载 hello = reload(hello) Python 2

__name__ = '__main__'

import sys, pprint
pprint.pprint(sys.path)
  • 设置系统变量 PYTHONPATH

  • .pth 路径配置文件

  • 包 __init__.py

  • 模块的一些内建方法 dir __all__ help

import copy

dir(copy)

[n for n in dir(copy) if not n.startswith('_')]

copy.__all__

# 可以使用 * 引入 __all__ 里面的函数,直接使用。
# 不在 __all__ 只能显式引入
from copy import *

help(copy.copy)

copy.copy.__doc__

copy.__file__

常用模块
  • sys
  • os
  • fileinput
  • set heapq deque
  • time
  • random
  • shelve
  • re

10 文件

11 GUI

12 数据库

13 网络编程

14 Web

15 测试

16 扩展

17 打包

End

更新时间:2025-03-13 13:26:33