1. 程式人生 > >Python3_高階特性學習_1

Python3_高階特性學習_1

前言

斷斷續續兩個周, 終於比對著敲了一遍.
相對源文件的一些python2實現,轉成了python3.
有一些問題尚未解決,如有了解,也請不吝賜教,我會盡快更新.
原文文件
GIthub原始檔

後續: python 推導式 Mutation/Immutation virtualenv Collections

Learning Code

# Python 進階

# 1 可選引數
# 使用:函式裝飾器,猴子補丁(程式執行時(runtime)修改某些程式碼)
# *args
def test_asterisk(f_arg, *arg_vars):
    print('f_arg', f_arg)
    for arg in arg_vars:
        print('arg in arg_vars', arg)


test_asterisk('yasoob', 'python', 'eggs', 'test')
# **dargs: 只能單獨使用
def test_kvps(**arg_vars):
    for (key, v) in arg_vars.items():
        print("{0} == {1}".format(key, v))

test_kvps(**{'name': 'yasoob'})
# 同時使用時的順序不能改變
def test_args(arg1, *arg2, **arg3):
    print('f_arg', arg1)
    for arg in arg2:
        print('arg in arg_vars', arg)
    for (key, v) in arg3.items():
        print("{0} == {1}".format(key, v))
test_args('yasoob', 'python', 'eggs', 'test', 123123, **{'name': 'yasoob'})


# 2 Debugging
'''
    python -m pdb my_script.py
    c:continue 繼續執行
    w:where 顯示當前正在執行的程式碼行的上下文資訊
    a:args 列印當前函式的引數列表
    s:step 執行當前程式碼行,並停在第一個能停的地方(相當於單步進入)
    n:next 繼續執行到當前函式的下一行,或者當前行直接返回(單步跳過)
    p:print  p expression
'''


# 3 生成器(Generators)
'''
迭代(Iteration):當我們使用一個迴圈來遍歷某個東西的過程
迭代器(Iterator): 遍歷一個容器(特別是列表)的物件,
    定義了next(Python2) 或者__next__方法的物件
可迭代物件(Iterable): 能提供迭代器的任意物件,
    定義了可以返回一個迭代器的__iter__方法,或者可以支援下標索引的__getitem__方法
生成器(Generators): 生成器是隻迭代一次的迭代器.這是因為它們並沒有把所有的值存在記憶體中,而是在執行時生成值.
    通過yield每次返回一個單次執行的值, 而不是直接返回佔用大量空間的一個值
    呼叫:用for迴圈,或可進行迭代的函式或結構
    next(): 它允許我們獲取一個序列的下一個元素. yield所有值後會觸發 StopIteration exception
'''
def fibon(n):
    a = b = 1
    for i in range(n):
        yield a
        (a, b) = (b, a+b)
i = 0
for x in fibon(10):
    i += 1
    print('fibon({0})'.format(i), x)
test_string = 'te'
test = iter(test_string)
print(next(test))
print(next(test))
# print(next(test) ) # StopIteration
# iter and next implement
class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]


# 4 Map:n個輸入源返回n個結果 將函式對映到集合的每個元素,多與lambda連用
# map(function_to_apply, list_of_inputs)
# lambda:匿名函式 
# 引數:操作(引數)
items = [1, 2, 3, 4, 5]
squard = list(map(lambda x: x**2, items))
print(squard)
# 將多個函式對映到集合
def multiply(x): return (x**2)
def add(x): return (x*2)
funcs = [multiply, add]
for i in range(5):
    # 函式作為lambda的操作物件
    value = map(lambda x: x(i), funcs)
    print(list(value))

# Filter: 過濾表中的元素, 返回所有符合要求的元素 
# filter(function, iterable)
# 可用推導式替換,推導式的可讀性更好
pr = filter(lambda x: 1==1, range(-5,5))
print(list(pr))

# Reduce 多個輸入源返回一個結果,對一個列表計算返回結果:第一個元素與第二個計算,其結果與第三個元素運算
# reduce(function, iterable[, initializer])
from functools import reduce
pro = reduce(lambda x,y:x*y, range(1, 5))
print(pro)


# 5 資料結構
# strings, list, tuple, dictionary
# number:int float bool 
# string 'name' 不可變,不可以對其中的字元賦值; 多用list替代 可切片
# list [1, 2, 3] 可變,key必須是數字,可以對其組成元素進行增刪改 可切片
# tuple (0, 1, 2) 不可變,常用於return返回的結果,形參,字典鍵, 可切片
# dict {'name':'zhangsan', 'age':20} 可變,key可以是string等非數字 {}
# set {1,2,3} 元素不可以重複,不能切片, 運算的單位是集合
# set 集合:不能包含重複的值 不能切片
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
dup = set([x for x in some_list if some_list.count(x) > 1])
print(dup)
# set intersection 交集
valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.intersection(valid))
# set difference 差集
print(input_set.difference(valid))


# 6 三元運算子
# 如果條件為真,返回真 否則返回假 
# condition_is_true if condition else condition_is_false
is_fat = True
print('fat' if is_fat else 'not fat')
# 結合元組使用 true means 1, 因為元組要先建資料,所以兩個表示式都會執行
print(('skinny','fat')[is_fat])


# 7 裝飾器
# 一切皆物件:物件可以作為賦值給變數或是作為引數傳遞給函式(類似js)
# 不同語言對物件的定義不同,python中的物件只要有屬性或方法就可以,不要求可子類化,
def hi(name='benji'):
    return 'hi '+name
print(hi())
greet = hi #greet不是呼叫hi函式,而是分配到新的記憶體
print(greet())
del hi
#print(hi()) #NameError: name 'hi' is not defined
print(greet())
# 巢狀函式
def hi2(name='benji'):
    print('context is in hi()')
    def greet2():
        print('context is in greet()')
    greet2()
    print('context is in hi() again')

hi2()
# greet2() #NameError: name 'greet2' is not defined

# 返回函式
def hi3(name='benji'):
    def greet3(): return 'greet3 ' + name
    def welcome3(): return 'welcome3'
    if name == 'benji':
        return welcome3
    else:
        return greet3
a = hi3()
print(a) #<function hi3.<locals>.greet3 at 0x00DAD7C8>
print(a())

# 函式作為引數
def fun_as_var(func):
    print('fun_as_var')
    func()
fun_as_var(hi2)

# Python 裝飾器: 封裝一個函式, 圍繞函式,做一些操作
# @decorator: 以單個函式作為引數的一個包裹函式
from functools import wraps
def new_decorator(a_func):
    @wraps(a_func) #恢復被裝飾函式的名字和註釋文件
    def wrap_func():
        print('before para function in new_decoration ')
        a_func()
        print('after para function in new_decoration ')
    return wrap_func
def a_func():
    print('in function needed to be decorated')
new_decorator(a_func)()
@new_decorator
def a_func_with_deco():
    print('in a_func_with_deco, function needed to be decorated')
a_func_with_deco()
print(a_func_with_deco.__name__)#wrap_func restore by functools.wraps

# decorator sample
from functools import wraps
def decorator_name(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        print('run in decorator_name')
        if not can_run:
            return 'function will not run'
        return f(*args, **kwargs)
    return decorated
@decorator_name
def func(*arg2, **arg3):
    for arg in arg2:
        print('arg in arg_vars', arg)
    for (key, v) in arg3.items():
        print("{0} == {1}".format(key, v))
    return 'function is running'
can_run = True
print(func(12,'test','asdf'))    

# 使用場景
'''# 授權

def require_auth(f):
    @warps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            authenticate()
        return f(*args, **kwargs)
    return decorated
'''
# 日誌
def logit_easy(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + ' was called')
        return func(*args, **kwargs)
    return with_logging
@logit_easy
def addition_func(x):
    return x+x
print(addition_func(4))
# 帶引數的裝飾器
# 裝飾器方法本身需要接收函式作為入參,為避免形參衝突,再巢狀一層函式用來接收其他入參
from functools import wraps
def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def warp_function(*args, **kwargs):
            log_string = func.__name__ + ' was called.'
            print(log_string)
            with open(logfile, 'a') as opened_file:
                opened_file.write(log_string+'\n')
            return func(*args, **kwargs)
        return warp_function
    return logging_decorator
@logit()
def myfunc1():
    pass
myfunc1()
@logit(logfile='func2.log')
def myfunc2():
    pass
myfunc2()

# Decorate Class 
# 裝飾類程式碼比裝飾函式簡潔,易於拓展,包裹函式可以通過類屬性獲取新功能的引數,不需要巢狀函式
# __call__()方法能夠讓類的例項物件,像函式一樣被呼叫
class logitClass(object): 
    def __init__(self, logfile='out2.log'):
        self.logfile = logfile
    def __call__(self, func):
        @wraps(func)
        def warp_function(*args, **kwargs):
            log_string = func.__name__ + ' was called'
            print(log_string, self.logfile)
            with open(self.logfile, 'a') as opened_file:
                opened_file.write(log_string+'\n')
            self.notify()
            return func(*args, **kwargs)
        return warp_function
    def notify(self):
        print('super notify')
        
# 包裹函式的語法與之前一致
@logitClass()
def myclass1func():
    pass
myclass1func()

class email_logit(logitClass):
    def __init__(self, email='
[email protected]
', *args, **kwargs): self.email = email print('email_logit',args) for i in args: print('email_logit',i) logitClass.__init__(self, *args, **kwargs) def notify(self): print('this is in child class email logit') # ??? 子類如何設定log檔名稱 # invalid @email_logit('email.log') @email_logit() def myclassEmail(): pass myclassEmail()

相關連結

Python 進階
英文版: Python Tips
The Python Debugger
ipython_memory_usage IPython tool to report memory usage deltas for every command you type.
virtual DOC
ctypes A foreign function library for Python
swig tutorial
Python/C API This manual documents the API used by C and C++ programmers who want to write extension modules or embed Python


smartcd Alter your bash (or zsh) environment as you cd
coroutine Coroutines.pdf