python的一些小技巧

顯示有限的接口到外部

當(dāng)發(fā)布python第三方package時(shí), 并不希望代碼中所有的函數(shù)或者class可以被外部import, 在__init__.py中添加__all__屬性,

該list中填寫(xiě)可以import的類或者函數(shù)名, 可以起到限制的import的作用, 防止外部import其他函數(shù)或者類

#!/usr/bin/env python

# -*- coding: utf-8 -*-

from base import APIBase

from client import Client

from decorator import interface, export, stream

from server import Server

from storage import Storage

from util import (LogFormatter, disable_logging_to_stderr,

enable_logging_to_kids, info)

__all__ = ['APIBase', 'Client', 'LogFormatter', 'Server',

'Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids',

'export', 'info', 'interface', 'stream']

with的魔力

with語(yǔ)句需要支持上下文管理協(xié)議的對(duì)象, 上下文管理協(xié)議包含__enter__和__exit__兩個(gè)方法. with語(yǔ)句建立運(yùn)行時(shí)上下文需要通過(guò)這兩個(gè)方法執(zhí)行進(jìn)入和退出操作.

其中上下文表達(dá)式是跟在with之后的表達(dá)式, 該表示大返回一個(gè)上下文管理對(duì)象

# 常見(jiàn)with使用場(chǎng)景

with open("test.txt", "r") as my_file:? # 注意, 是__enter__()方法的返回值賦值給了my_file,

for line in my_file:

print line

詳細(xì)原理可以查看這篇文章,淺談 Python 的 with 語(yǔ)句

知道具體原理, 我們可以自定義支持上下文管理協(xié)議的類, 類中實(shí)現(xiàn)__enter__和__exit__方法

#!/usr/bin/env python

# -*- coding: utf-8 -*-

class MyWith(object):

def __init__(self):

print "__init__ method"

def __enter__(self):

print "__enter__ method"

return self? # 返回對(duì)象給as后的變量

def __exit__(self, exc_type, exc_value, exc_traceback):

print "__exit__ method"

if exc_traceback is None:

print "Exited without Exception"

return True

else:

print "Exited with Exception"

return False

def test_with():

with MyWith() as my_with:

print "running my_with"

print "------分割線-----"

with MyWith() as my_with:

print "running before Exception"

raise Exception

print "running after Exception"

if __name__ == '__main__':

test_with()

執(zhí)行結(jié)果如下:

__init__ method

__enter__ method

running my_with

__exit__ method

Exited without Exception

------分割線-----

__init__ method

__enter__ method

running before Exception

__exit__ method

Exited with Exception

Traceback (most recent call last):

File "bin/python", line 34, in

exec(compile(__file__f.read(), __file__, "exec"))

File "test_with.py", line 33, in

test_with()

File "test_with.py", line 28, in test_with

raise Exception

Exception

證明了會(huì)先執(zhí)行__enter__方法, 然后調(diào)用with內(nèi)的邏輯, 最后執(zhí)行__exit__做退出處理, 并且, 即使出現(xiàn)異常也能正常退出

filter的用法

相對(duì)filter而言, map和reduce使用的會(huì)更頻繁一些,filter正如其名字, 按照某種規(guī)則過(guò)濾掉一些元素

#!/usr/bin/env python

# -*- coding: utf-8 -*-

lst = [1, 2, 3, 4, 5, 6]

# 所有奇數(shù)都會(huì)返回True, 偶數(shù)會(huì)返回False被過(guò)濾掉

print filter(lambda x: x % 2 != 0, lst)

#輸出結(jié)果

[1, 3, 5]

一行作判斷

當(dāng)條件滿足時(shí), 返回的為等號(hào)后面的變量, 否則返回else后語(yǔ)句

lst = [1, 2, 3]

new_lst = lst[0] if lst is not None else None

print new_lst

# 打印結(jié)果

1

裝飾器之單例

使用裝飾器實(shí)現(xiàn)簡(jiǎn)單的單例模式

# 單例裝飾器

def singleton(cls):

instances = dict()? # 初始為空

def _singleton(*args, **kwargs):

if cls not in instances:? #如果不存在, 則創(chuàng)建并放入字典

instances[cls] = cls(*args, **kwargs)

return instances[cls]

return _singleton

@singleton

class Test(object):

pass

if __name__ == '__main__':

t1 = Test()

t2 = Test()

# 兩者具有相同的地址

print t1, t2

staticmethod裝飾器

類中兩種常用的裝飾, 首先區(qū)分一下他們

普通成員函數(shù), 其中第一個(gè)隱式參數(shù)為對(duì)象

classmethod裝飾器, 類方法(給人感覺(jué)非常類似于OC中的類方法), 其中第一個(gè)隱式參數(shù)為類

staticmethod裝飾器, 沒(méi)有任何隱式參數(shù).python中的靜態(tài)方法類似與C++中的靜態(tài)方法

#!/usr/bin/env python

# -*- coding: utf-8 -*-

class A(object):

# 普通成員函數(shù)

def foo(self, x):

print "executing foo(%s, %s)" % (self, x)

@classmethod? # 使用classmethod進(jìn)行裝飾

def class_foo(cls, x):

print "executing class_foo(%s, %s)" % (cls, x)

@staticmethod? # 使用staticmethod進(jìn)行裝飾

def static_foo(x):

print "executing static_foo(%s)" % x

def test_three_method():

obj = A()

# 直接調(diào)用噗通的成員方法

obj.foo("para")? # 此處obj對(duì)象作為成員函數(shù)的隱式參數(shù), 就是self

obj.class_foo("para")? # 此處類作為隱式參數(shù)被傳入, 就是cls

A.class_foo("para")? #更直接的類方法調(diào)用

obj.static_foo("para")? # 靜態(tài)方法并沒(méi)有任何隱式參數(shù), 但是要通過(guò)對(duì)象或者類進(jìn)行調(diào)用

A.static_foo("para")

if __name__ == '__main__':

test_three_method()

# 函數(shù)輸出

executing foo(<__main__.A object at 0x100ba4e10>, para)

executing class_foo(, para)

executing class_foo(, para)

executing static_foo(para)

executing static_foo(para)

property裝飾器

定義私有類屬性

將property與裝飾器結(jié)合實(shí)現(xiàn)屬性私有化(更簡(jiǎn)單安全的實(shí)現(xiàn)get和set方法)

#python內(nèi)建函數(shù)

property(fget=None, fset=None, fdel=None, doc=None)

fget是獲取屬性的值的函數(shù),fset是設(shè)置屬性值的函數(shù),fdel是刪除屬性的函數(shù),doc是一個(gè)字符串(like a comment).從實(shí)現(xiàn)來(lái)看,這些參數(shù)都是可選的

property有三個(gè)方法getter(),setter()和delete()來(lái)指定fget, fset和fdel。 這表示以下這行

class Student(object):

@property? #相當(dāng)于property.getter(score) 或者property(score)

def score(self):

return self._score

@score.setter #相當(dāng)于score = property.setter(score)

def score(self, value):

if not isinstance(value, int):

raise ValueError('score must be an integer!')

if value < 0 or value > 100:

raise ValueError('score must between 0 ~ 100!')

self._score = value

iter魔法

通過(guò)yield和__iter__的結(jié)合, 我們可以把一個(gè)對(duì)象變成可迭代的

通過(guò)__str__的重寫(xiě), 可以直接通過(guò)想要的形式打印對(duì)象

#!/usr/bin/env python

# -*- coding: utf-8 -*-

class TestIter(object):

def __init__(self):

self.lst = [1, 2, 3, 4, 5]

def read(self):

for ele in xrange(len(self.lst)):

yield ele

def __iter__(self):

return self.read()

def __str__(self):

return ','.join(map(str, self.lst))

__repr__ = __str__

def test_iter():

obj = TestIter()

for num in obj:

print num

print obj

if __name__ == '__main__':

test_iter()

神奇partial

partial使用上很像C++中仿函數(shù)(函數(shù)對(duì)象).

在stackoverflow給出了類似與partial的運(yùn)行方式

def partial(func, *part_args):

def wrapper(*extra_args):

args = list(part_args)

args.extend(extra_args)

return func(*args)

return wrapper

利用用閉包的特性綁定預(yù)先綁定一些函數(shù)參數(shù), 返回一個(gè)可調(diào)用的變量, 直到真正的調(diào)用執(zhí)行

#!/usr/bin/env python

# -*- coding: utf-8 -*-

from functools import partial

def sum(a, b):

return a + b

def test_partial():

fun = partial(sum, 2)? # 事先綁定一個(gè)參數(shù), fun成為一個(gè)只需要一個(gè)參數(shù)的可調(diào)用變量

print fun(3)? # 實(shí)現(xiàn)執(zhí)行的即是sum(2, 3)

if __name__ == '__main__':

test_partial()

# 執(zhí)行結(jié)果

5

神秘eval

eval我理解為一種內(nèi)嵌的python解釋器(這種解釋可能會(huì)有偏差), 會(huì)解釋字符串為對(duì)應(yīng)的代碼并執(zhí)行, 并且將執(zhí)行結(jié)果返回

看一下下面這個(gè)例子

#!/usr/bin/env python

# -*- coding: utf-8 -*-

def test_first():

return 3

def test_second(num):

return num

action = {? # 可以看做是一個(gè)sandbox

"para": 5,

"test_first" : test_first,

"test_second": test_second

}

def test_eavl():

condition = "para == 5 and test_second(test_first) > 5"

res = eval(condition, action)? # 解釋condition并根據(jù)action對(duì)應(yīng)的動(dòng)作執(zhí)行

print res

if __name__ == '_

exec

exec在Python中會(huì)忽略返回值, 總是返回None, eval會(huì)返回執(zhí)行代碼或語(yǔ)句的返回值

exec和eval在執(zhí)行代碼時(shí), 除了返回值其他行為都相同

在傳入字符串時(shí), 會(huì)使用compile(source, '', mode)編譯字節(jié)碼. mode的取值為exec和eval

#!/usr/bin/env python

# -*- coding: utf-8 -*-

def test_first():

print "hello"

def test_second():

test_first()

print "second"

def test_third():

print "third"

action = {

"test_second": test_second,

"test_third": test_third

}

def test_exec():

exec "test_second" in action

if __name__ == '__main__':

test_exec()? # 無(wú)法看到執(zhí)行結(jié)果

getattr

getattr(object, name[, default])Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

通過(guò)string類型的name, 返回對(duì)象的name屬性(方法)對(duì)應(yīng)的值, 如果屬性不存在, 則返回默認(rèn)值, 相當(dāng)于object.name

# 使用范例

class TestGetAttr(object):

test = "test attribute"

def say(self):

print "test method"

def test_getattr():

my_test = TestGetAttr()

try:

print getattr(my_test, "test")

except AttributeError:

print "Attribute Error!"

try:

getattr(my_test, "say")()

except AttributeError: # 沒(méi)有該屬性, 且沒(méi)有指定返回值的情況下

print "Method Error!"

if __name__ == '__main__':

test_getattr()

# 輸出結(jié)果

test attribute

test method

命令行處理

defprocess_command_line(argv):

"""

Return a 2-tuple: (settings object, args list).

`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.

"""

ifargvisNone:

argv = sys.argv[1:]

# initialize the parser object:

parser = optparse.OptionParser(

formatter=optparse.TitledHelpFormatter(width=78),

add_help_option=None)

# define options here:

parser.add_option(# customized description; put --help last

'-h','--help', action='help',

help='Show this help message and exit.')

settings, args = parser.parse_args(argv)

# check number of arguments, verify values, etc.:

ifargs:

parser.error('program takes no command-line arguments; '

'"%s" ignored.'% (args,))

# further process settings & args if necessary

returnsettings, args

defmain(argv=None):

settings, args = process_command_line(argv)

# application code here, like:

# run(settings, args)

return0# success

if__name__ =='__main__':

status = main()

sys.exit(status)

讀寫(xiě)csv文件

# 從csv中讀取文件, 基本和傳統(tǒng)文件讀取類似

import csv

with open('data.csv', 'rb') as f:

reader = csv.reader(f)

for row in reader:

print row

# 向csv文件寫(xiě)入

import csv

with open( 'data.csv', 'wb') as f:

writer = csv.writer(f)

writer.writerow(['name', 'address', 'age'])? # 單行寫(xiě)入

data = [

( 'xiaoming ','china','10'),

( 'Lily', 'USA', '12')]

writer.writerows(data)? # 多行寫(xiě)入

各種時(shí)間形式轉(zhuǎn)換

只發(fā)一張網(wǎng)上的圖, 然后差文檔就好了, 這個(gè)是記不住的

字符串格式化

一個(gè)非常好用, 很多人又不知道的功能

>>> name = "andrew"

>>> "my name is {name}".format(name=name)

'my name is andrew'

# 還可以是?

"my name is {0}".format(name)

參考鏈接

What is the difference between @staticmethod and @classmethod in Python?

Python @property versus getters and setters

How does the @property decorator work?

How does the functools partial work in Python?

What’s the difference between eval, exec, and compile in Python?

Be careful with exec and eval in Python

Python (and Python C API):newversusinit

Python ‘self’ keywordself不是關(guān)鍵字, 是一個(gè)約定的變量名

Python進(jìn)階必讀匯總

使python類可以判斷真值

Best Python Resources

Python安全編碼指南


轉(zhuǎn)摘自:http://andrewliu.in/2015/11/14/Python%E5%A5%87%E6%8A%80%E6%B7%AB%E5%B7%A7/

作者在簡(jiǎn)書(shū)的地址:http://www.lxweimin.com/u/4ee453b72aff

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,345評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,494評(píng)論 3 416
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 176,283評(píng)論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 62,953評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,714評(píng)論 6 410
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 55,186評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評(píng)論 3 441
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 42,410評(píng)論 0 288
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,940評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,776評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,976評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評(píng)論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,210評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 34,642評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 35,878評(píng)論 1 286
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,654評(píng)論 3 391
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,958評(píng)論 2 373

推薦閱讀更多精彩內(nèi)容