Skip to content

basic

豆知识

命名来源于 the BBC show “Monty Python’s Flying Circus” and has nothing to do with reptiles 哦!

安装

  • 安装超方便的 注意 python3 自带了 pip3 的包管理器
  • 插件:pip3 install autopepe8; pip3 install flake

语法

Python 好简单,所以直接看文档就挺快的 https://docs.python.org/3/tutorial/index.html

由于全局锁 GIL,所以 Python 的多线程程序在同一时间只有一个线程在运行,因此它只是并发,而不是并行。要实现并行的话,要么使用多进程,要么使用 Cython 等库调用 C++ 代码,要么还可以更换没有 GIL 的解释器 🤣 Ref

p.s. 计算密集型 vs IO 密集型(web应用)的概念

关于模块 Python is called as "battries included." 就是因为有很多内建模块

  • python -m module [arg] ...

循环

  • for ... in slices / maps.copy().items() / range(5)
  • pass
  • switch/case => match/case..if x == y

function/def

  • The default value 默认只会被初始化一次,因此在 list, dictionary 或实例的情况下会被重复使用. To avoid:
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
  • 参数还可以命名!
    • def pos_only_arg(arg, /):
    • def kwd_only_arg(*, arg):
    • def foo(name, **kwds):
  • lambda:
def make_incrementor(n):
     return lambda x: x + n

Data Structures

Lists []

  • list.pop() / popleft()
  • 循环
    • for i, v in enumerate(['tic', 'tac', 'toe']):
    • 同时: for q, a in zip(questions, answers):
  • 快速 create
squares = list(map(lambda x: x**2, range(10)))
squares = [x**2 for x in range(10)]
combs = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] # 还可以这么连!

Tuples ()

immutable

empty = ()
singleton = 'hello',    # <-- note trailing comma

Sets {}

Dictionaries {}

  • list(adict)
  • dict(sape=4139, guido=4127, jack=4098)
  • for k, v in knights.items():

Modules & Packages

  • Module: 单个文件
    • import module0 as m0
    • from module1 import module_info as mi
  • Package: 含有 __init__.py 的文件夹
    • import package1.module0 as p1_m0
# __init_.py
__all__ = ["echo", "surround", "reverse"] # 以支持 from sound.effects import *

异常

try...raise..except

Class

class MyClass:
    """A simple example class"""
    i = 12345 # static method

    def f(self):
        return 'hello world'

    def __init__(self, x): # constructor
        self.data = x 

x = MyClass()

库大全

文件与路径

import os
from os import path
import shutil

# Path at terminal
print(os.getcwd() + "\n")

# file path
print(__file__ + "\n")

# full file path
full_path = path.realpath(__file__)
print(full_path + "\n")

# directory
path.dirname(full_path)

# dir_name
path.basename(full_path)

# 读取相对当前文件的路径
path.realpath(path.join(path.dirname(__file__), '../images'))

# 复制
shutil.copyfile(...)
shutil.copytree(...)