python 基础

python的单例模式

  • 修改__new__(cls)静态方法
class A(object):
    __instance = None

    def __new__(cls):
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        return cls.__instance

python的继承

  • python的子类会继承父类公开的方法和魔法方法
  • 类属性是属于类的, 所以公开的也会被继承
  • 类属性只能被类修改和删除
  • 在__init__方法中调用super().__init__(父类的参数列表)
  • 定义接口的话, 则在父类方法的实现使用pass关键字

python的异常处理


try:

except Exception as ex:

finally:
    
  • 抛出异常
    • raise MyException('Error')

python的属性命名

  • 以_后缀

python的类方法与静态方法

  • 类方法

@classmethod
# test的第一个形参必须为cls
def test(cls):
    
  • 静态方法(特殊的类方法)

@staticmethod
# 不会传递默认的cls参数
def test():
    

初始化属性

  • property = None

继承基类的查找

  • obj.__mro__

搜索区域

  • locals -> globals -> builtins

在函数中修改全局变量

  • globals globl_val
  • globl_val = 10

访问一个对象的属性

  • 会通过__getattribute__魔法方法, 一不小心就是让挂了

闭包

  • 在一个函数中定义函数, 并返回该函数

pdb使用

  • python -m pdb file.py
  • c, b, n, r, p

类修饰器


class Test(object):

    def __init__(self, func):
        print('Test init')
        self.__func = func

    def __callable__(self):
        print('Call...')
        self.__func()


@Test # 会将func作为传入到Test(func)中
def func():
    print('This is func function')

del语句的实质

  • del用来较少对象的引用, 与C++中的delete不同, delete是将指针指向的对象的内存空间释放掉

进程

  • import os

  • os.fork() 底层调用的是C中库函数fork()

  • 使用mutilprocessing.Process类的start()方法进行初始化

  • 继承Process类, 重写run方法

  • 使用进程池

  • Pool(size)

  • pool.apply_async(func, args=(), kwargs={}) # 进程不等待

  • pool.apply() # 进程会阻塞

  • pool.close() # 关闭pool, 让pool不在接受请求

  • pool.terminate() # 终止任务

  • pool.join() # 等待子进程

线程

  • import threading
  • 调用th = threading.Thread(target=work, args=(), kwargs={})
  • th.start()
  • threading.current_thread().name
  • threading.current_thread().getName(), isAlive(), setName()
  • th.join()
  • th.terminate()
  • 采用继承的方式实现线程
  • 继承threading.Thread, 重载run方法

线程锁

  • mutex = threading.Lock()
  • mutex.acquire()
  • mutex.release()

线程队列

  • import queue
  • queue.Queue中的元素存取的时候都是线程安全的, 所以一般线程安全的获取资源就是使用Queue
  • q.put(), q.get()
  • 该queue是自定义线程池的基础, 首先一个while中不断get进程start, 后面在加上thread

套接字编程(socket就是API)

  • 类: socket.socket()
  • 方法: s.sendto(), s.recvfrom()

注意点

  • fork出来的进程有自己独立的内存空间, 与线程是不同的
原文地址:https://www.cnblogs.com/megachen/p/9741767.html