pythone 学习知识整理

python 的多线程、多进程学习总结

基本概念

  1. 进程

一个运行的程序称做进程

给函数的执行计时(装饰器实现)

这是利用装饰器的特性来,来完成对函数执行完成的计算。

import time

def fn_timer(func):
    def function_timer(*args, **kwargs):
        t0 = time.time()
        result = func(*args, **kwargs)
        t1 = time.time()
        print("Total time running '{func_name}': {time} secondes".format(
            func_name=func.__name__, time=str(t1-t0)[:9]
        ))
        return result
    return function_timer

@fn_timer
def print_11():
    print('11')
    
print_11()
11
Total time running 'print_11': 6.4134597 secondes

python 多进程(demo)

import multiprocessing
import time


def clock_1(interval):
    while True:
        print('--1--: The time is :', time.ctime())
        time.sleep(interval)
        
        
def clock_2(interval):
    while True:
        print('--2--: The time is :', time.ctime())
        time.sleep(interval)

print('This is a test for multiprocessing')
p1 = multiprocessing.Process(target=clock_1, args=(3,))
p1.start()

p2 = multiprocessing.Process(target=clock_2, args=(4,))
p2.start()
print('SubProcess is going to start')
time.sleep(16)
print('SubProcess is going to be shutdown')
p1.terminate()
print('Clock_1 has been terminated')
p2.terminate()
print('Clock_2 has been terminated')
print('1 pid is:', p1.pid)
print('2-SubProcess name is', p2.name)
print('2-ExitCode is', p2.exitcode)

This is a test for multiprocessing
--1--: The time is : Sun Dec 24 17:35:49 2017
--2--: The time is : Sun Dec 24 17:35:49 2017
SubProcess is going to start
--1--: The time is : Sun Dec 24 17:35:52 2017
--2--: The time is : Sun Dec 24 17:35:53 2017
--1--: The time is : Sun Dec 24 17:35:55 2017
--2--: The time is : Sun Dec 24 17:35:57 2017
--1--: The time is : Sun Dec 24 17:35:58 2017
--2--: The time is : Sun Dec 24 17:36:01 2017
--1--: The time is : Sun Dec 24 17:36:01 2017
--1--: The time is : Sun Dec 24 17:36:04 2017
SubProcess is going to be shutdown
Clock_1 has been terminated
Clock_2 has been terminated
1 pid is: 40102
2-SubProcess name is Process-3
2-ExitCode is None

python 进程间通信

import multiprocessing
import time


def adder(pipe):
    print('Server SubProcess start ...')
    server_p, client_p = pipe
    client_p.close()
    
    while True:
        try:
            x, y = server_p.recv()
        except EOFError:
            print(str(EOFError))
            time.sleep(5)
            break
        result = x + y
        server_p.send(result)
    print('Server done ...')
    
if __name__ == '__main__':
    (server_p, client_p) = multiprocessing.Pipe()
    print('Pipe Created ...')
    time.sleep(3)
    adder_p = multiprocessing.Process(target=adder, args=((server_p, client_p),))
    adder_p.start()
    server_p.close()

    print('Begin to test...')
    client_p.send((9, 9))
    time.sleep(1)
    print(client_p.recv())

    client_p.send(('You','UP!'))
    print(client_p.recv())

    time.sleep(5)
    client_p.close()
    #if MainProcess shutdown, the SubProcess created by it will also be shutdown
    #So U should wait until the SubProcess done...
    adder_p.join()

    input('Enter for Exit...')
Pipe Created ...
Server SubProcess start ...
Begin to test...
18
YouUP!
<class 'EOFError'>
Server done ...
Enter for Exit...

Python 高级编程

第二章

生成器模版

def my_generator():
    try:
        yield 'something'
    except ValueError:
        yield 'dealing with the exception'
    finally:
        print("ok let's clean")
gen = my_generator()
gen.__next__()
'something'

生成器表达式

iter_list = (x**2 for x in range(10) if x % 2 == 0)
for el in iter_list:
    print(el)
0
4
16
36
64

装饰器

# 简单装饰器
def mydecorator(func):
    def _mydecorator(*args, **kwargs):
        res = func(*args, **kwargs)
        return res
    return _mydecorator

带参数的简单装饰器

def mydecorator(arg1, arg2):
    def _mydecorator(func):
        def __mydecorator(*args, **kwargs):
            res = func(*args, **kwargs)
            return res
        return __mydecorator
    return _mydecorator

第三章

子类化内建类型

class DistinctError(Exception):
    pass


class distincdict(dict):
    def __setitem__(self, key, value):
        try:
            value_index = list(self.values()).index(value)
            existing_key = list(self.keys())[value_index]
            if existing_key != key:
                raise DistinctError(("This value already exists for '%s'") % str(self[existing_key]))
        except ValueError:
            pass
        
        super(distincdict, self).__setitem__(key, value)
        
        
my = distincdict()
my['key'] = 'value'
my['other_key'] = 'value'
    
---------------------------------------------------------------------------

DistinctError                             Traceback (most recent call last)

<ipython-input-62-9f4b19dff490> in <module>()
     18 my = distincdict()
     19 my['key'] = 'value'
---> 20 my['other_key'] = 'value'
     21 


<ipython-input-62-9f4b19dff490> in __setitem__(self, key, value)
      9             existing_key = list(self.keys())[value_index]
     10             if existing_key != key:
---> 11                 raise DistinctError(("This value already exists for '%s'") % str(self[existing_key]))
     12         except ValueError:
     13             pass


DistinctError: This value already exists for 'value'

访问超类中的方法

class Mama():
    def says(self):
        print('Do your homework')
        
        
class Sister(Mama):
    def says(self):
        super().says()
        print('and clean your bedroom')
        
        
anita = Sister()
anita.says()
Do your homework
and clean your bedroom
MyType = type('MyType', (object,), {'a': 1})
ob = MyType()
type(ob)
ob.a
1

单例模式

class Singleton():
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance
    
    
class MyClass(Singleton):
    a = 1
    

one = MyClass()
two = MyClass()
one.a = 3
two.a
3

Python 中的 classmethod 和 staticmethod 有什么具体用途?

## 类方法用途展示,可以方位类属性
class Kls:
    no_inst = 0
    def __init__(self):
        Kls.no_inst = Kls.no_inst + 1
    
    @classmethod
    def get_no_of_instacne(cls):
        return cls.no_inst
        
ik1 = Kls()
print(ik1.get_no_of_instacne())
ik2 = Kls()
print(ik2.get_no_of_instacne())
print(Kls.get_no_of_instacne())
1
2
2

python 装饰器官方示例

Creating Well-Behaved Decorators / "Decorator decorator"

def simple_decorator(decorator):
    def new_decorator(f):
        g = decorator(f)
        g.__name__ = f.__name__
        g.__doc__ = f.__doc__
        g.__dict__.update(f.__dict__)
        return g
    
    new_decorator.__name__ = decorator.__name__
    new_decorator.__doc__ = decorator.__doc__
    new_decorator.__dict__.update(decorator.__dict__)
    return new_decorator


@simple_decorator
def my_simple_logging_decorator(func):
    def you_will_never_see_this_name(*args, **kwargs):
        print('Calling {}'.format(func.__name__))
        return func(*args, **kwargs)
    return you_will_never_see_this_name


@my_simple_logging_decorator
def double(x):
    'Doubles a number'
    return 2 * x

assert double.__name__ == 'double'
assert double.__doc__ == 'Doubles a number'
print(double(155))
Calling double
310

Property Definition

import sys


def propget(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(func, doc=func.__doc__)
    else:
        doc = prop.__doc__ or func.__doc__
        prop = property(func, prop.fset, prop.fdel)
    return prop


def propset(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(None, func, doc=func.__doc__)
    else:
        doc = prop.__doc__ or func.__doc__
        prop = property(prop.fget, func, prop.fdel, doc)
    return prop


def propdel(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(None, None, func, doc=func.__doc__)
    else:
        prop = property(prop.fget, prop.fset, func, prop.__doc__)
    return prop


class Example():
    
    @propget
    def myattr(self):
        return self._half * 2
    
    @propset
    def myattr(self, value):
        self._half = value / 2
        
    @propdel
    def myattr(self):
        del self._half

Yet another property decorator

import builtins


def property(func):
    keys = 'fget', 'fset', 'fdel'
    func_locals = {'doc': func.__doc__}
    def probe_func(frame, event, arg):
        if event == 'return':
            locals = frame.f_locals
            func_locals.update(dict((k, locals.get(k)) for k in keys))
            sys.settrace(None)
        return probe_func
    sys.settrace(probe_func)
    func()
    return builtins.property(**func_locals)


from math import radians, degrees, pi


class Angle():
    def __init__(self, rad):
        self._rad = rad
        
    @property
    def rad():
        """The angle in radians"""
        def fget(self):
            return self._rad
        
        def fset(self, angle):
            if isinstance(angle, Angle):
                angle = angle.rad
            self._rad = float(angle)
        
        @property
        def deg():
            """The angle in degrees"""
            def fget(self):
                return degrees(self._rad)
            def fset(self, angle):
                if isinstance(angle, Angle):
                    angle = angle.deg
                self._rad = radians(angle)

Memoize

Here's a memoizing class.

import collections
import functools


class memoized():
    
    def __init__(self, func):
        self.func = func
        self.cache = {}
        
    def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
            return value
        
    def __repr__(self):
        '''Return the function's docstring'''
        return self.func.__doc__
    
    def __get__(self, obj, objtype):
        '''Support instance methods.'''
        return functools.partial(self.__call__, obj)
    
@memoized
def fibonacci(n):
    """Return the nth fibonacci number"""
    if n in (0, 1):
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(12))
144

Alternate memoize as nested functions

def memoize(obj):
    cache = obj.cache = {}
    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwrags)
        return cache[args]
    return memoizer

Here's a modified version that also respects kwargs.

def memoize(obj):
    cache = obj.cache = {}
    
    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = obj(*args, **kwargs)
        return cache[key]
    return memoizer

Alternate memoize as dict subclass

class memoize(dict):
    
    def __init__(self, func):
        self.func = func
        
    def __call__(self, *args):
        return self[args]
    
    def __missing__(self, key):
        result = self[key] = self.func(*key)
        return result
    
    
@memoize
def foo(a, b):
    return a, b

Alternate memoize that stores cache between executions

import pickle
import collections
import functools
import inspect
import os.path
import re
import unicodedata


class Memorize():
    
    def __init__(self, func):
        self.func = func
        self.set_parent_file()
        self.__name__ = self.func.__name__
        self.set_cache_filename()
        if self.cache_exists():
            self.read_cache()
            if not self.is_safe_cache():
                self.cache = {}
        else:
            self.cache = {}
            
    def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
            self.save_cache()
            return value
        
    def set_parent_file(self):
        rel_parent_file = inspect.stack()[-1].filename
        self.parent_filepath = os.path.abspath(rel_parent_file)
        self.parent_filename = _filename_from_path(rel_parent_file)
        
    def set_cache_filename(self):
        filename = _slugify(self.parent_filename.replace('.py', ''))
        funcname =  

python 装饰器官方示例

Creating Well-Behaved Decorators / "Decorator decorator"

def simple_decorator(decorator):
    def new_decorator(f):
        g = decorator(f)
        g.__name__ = f.__name__
        g.__doc__ = f.__doc__
        g.__dict__.update(f.__dict__)
        return g
    
    new_decorator.__name__ = decorator.__name__
    new_decorator.__doc__ = decorator.__doc__
    new_decorator.__dict__.update(decorator.__dict__)
    return new_decorator


@simple_decorator
def my_simple_logging_decorator(func):
    def you_will_never_see_this_name(*args, **kwargs):
        print('Calling {}'.format(func.__name__))
        return func(*args, **kwargs)
    return you_will_never_see_this_name


@my_simple_logging_decorator
def double(x):
    'Doubles a number'
    return 2 * x

assert double.__name__ == 'double'
assert double.__doc__ == 'Doubles a number'
print(double(155))
Calling double
310

Property Definition

import sys


def propget(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(func, doc=func.__doc__)
    else:
        doc = prop.__doc__ or func.__doc__
        prop = property(func, prop.fset, prop.fdel)
    return prop


def propset(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(None, func, doc=func.__doc__)
    else:
        doc = prop.__doc__ or func.__doc__
        prop = property(prop.fget, func, prop.fdel, doc)
    return prop


def propdel(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(None, None, func, doc=func.__doc__)
    else:
        prop = property(prop.fget, prop.fset, func, prop.__doc__)
    return prop


class Example():
    
    @propget
    def myattr(self):
        return self._half * 2
    
    @propset
    def myattr(self, value):
        self._half = value / 2
        
    @propdel
    def myattr(self):
        del self._half

Yet another property decorator

import builtins


def property(func):
    keys = 'fget', 'fset', 'fdel'
    func_locals = {'doc': func.__doc__}
    def probe_func(frame, event, arg):
        if event == 'return':
            locals = frame.f_locals
            func_locals.update(dict((k, locals.get(k)) for k in keys))
            sys.settrace(None)
        return probe_func
    sys.settrace(probe_func)
    func()
    return builtins.property(**func_locals)


from math import radians, degrees, pi


class Angle():
    def __init__(self, rad):
        self._rad = rad
        
    @property
    def rad():
        """The angle in radians"""
        def fget(self):
            return self._rad
        
        def fset(self, angle):
            if isinstance(angle, Angle):
                angle = angle.rad
            self._rad = float(angle)
        
        @property
        def deg():
            """The angle in degrees"""
            def fget(self):
                return degrees(self._rad)
            def fset(self, angle):
                if isinstance(angle, Angle):
                    angle = angle.deg
                self._rad = radians(angle)

Memoize

Here's a memoizing class.

import collections
import functools


class memoized():
    
    def __init__(self, func):
        self.func = func
        self.cache = {}
        
    def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
            return value
        
    def __repr__(self):
        '''Return the function's docstring'''
        return self.func.__doc__
    
    def __get__(self, obj, objtype):
        '''Support instance methods.'''
        return functools.partial(self.__call__, obj)
    
@memoized
def fibonacci(n):
    """Return the nth fibonacci number"""
    if n in (0, 1):
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(12))
144

Alternate memoize as nested functions

def memoize(obj):
    cache = obj.cache = {}
    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwrags)
        return cache[args]
    return memoizer

Here's a modified version that also respects kwargs.

def memoize(obj):
    cache = obj.cache = {}
    
    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = obj(*args, **kwargs)
        return cache[key]
    return memoizer

Alternate memoize as dict subclass

class memoize(dict):
    
    def __init__(self, func):
        self.func = func
        
    def __call__(self, *args):
        return self[args]
    
    def __missing__(self, key):
        result = self[key] = self.func(*key)
        return result
    
    
@memoize
def foo(a, b):
    return a, b

Alternate memoize that stores cache between executions

import pickle
import collections
import functools
import inspect
import os.path
import re
import unicodedata


class Memorize():
    
    def __init__(self, func):
        self.func = func
        self.set_parent_file()
        self.__name__ = self.func.__name__
        self.set_cache_filename()
        if self.cache_exists():
            self.read_cache()
            if not self.is_safe_cache():
                self.cache = {}
        else:
            self.cache = {}
            
    def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
            self.save_cache()
            return value
        
    def set_parent_file(self):
        rel_parent_file = inspect.stack()[-1].filename
        self.parent_filepath = os.path.abspath(rel_parent_file)
        self.parent_filename = _filename_from_path(rel_parent_file)
        
    def set_cache_filename(self):
        filename = _slugify(self.parent_filename.replace('.py', ''))
        funcname =  

Python 编程实战-运用设计模式、并发和程序库创建高质量程序

1.python 的创建型设计模式

1.1 抽象工厂模式

class DiagramFactory():
    
    def make_diagram(self, width, height):
        return Diagrame(width, height)
    
    def make_rectangle(self, x, y, width, height, fill="white", \
                       stroke="black"):
        return Rectangle(x, y, text, fontsize)
    
    def make_text(self, x, y, text, fontsize=1):
        return Text(x, y, text, fontsize)
    
    
class SvgDiagramFactory(DiagramFactory):
    def make_diagram(self, width, height):
        return SvgDiagram(width, height)


def create_diagram(factory):
    diagram = factory.make_diagram(30, 7)
    rectangle = factory.make_rectangle(4, 1, 22, 5, "yellow")
    text = factory.make_text(7, 3, "Abstact Factory")
    diagram.add(rectangle)
    diagram.add(text)
    return diagram


def main():
    textDiagram = create_diagram(DiagramFactory())
    txtDiagram.save(textFilename)
    
    svgDiagram = create_diagram(svgDiagramfactory())
    svgDiagram.save(svgFilename)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341