Python奇技淫巧

文章目錄
  1. 1. 顯示有限的接口到外部
  2. 2. with的魔力
  3. 3. filter的用法
  4. 4. 一行作判斷
  5. 5. 裝飾器之單例
  6. 6. staticmethod裝飾器
  7. 7. property裝飾器
  8. 8. iter魔法
  9. 9. 神奇partial
  10. 10. 神祕eval
  11. 11. exec
  12. 12. getattr
  13. 13. 命令行處理
  14. 14. 讀寫csv文件
  15. 15. 各種時間形式轉換
  16. 16. 字符串格式化
  17. 17. 參考鏈接

本博客採用創作共用版權協議, 要求署名、非商業用途和保持一致. 轉載本博客文章必須也遵循署名-非商業用途-保持一致的創作共用協議.

顯示有限的接口到外部

當發佈python第三方package時, 並不希望代碼中所有的函數或者class可以被外部import, 在__init__.py中添加__all__屬性,
該list中填寫可以import的類或者函數名, 可以起到限制的import的作用, 防止外部import其他函數或者類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/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語句需要支持上下文管理協議的對象, 上下文管理協議包含__enter____exit__兩個方法. with語句建立運行時上下文需要通過這兩個方法執行進入和退出操作.

其中上下文表達式是跟在with之後的表達式, 該表示大返回一個上下文管理對象

1
2
3
4
# 常見with使用場景
with open("test.txt", "r") as my_file: # 注意, 是__enter__()方法的返回值賦值給了my_file,
for line in my_file:
print line

詳細原理可以查看這篇文章, 淺談 Python 的 with 語句

知道具體原理, 我們可以自定義支持上下文管理協議的類, 類中實現__enter____exit__方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class MyWith(object):
def __init__(self):
print "__init__ method"
def __enter__(self):
print "__enter__ method"
return self # 返回對象給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()

執行結果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
__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 <module>
exec(compile(__file__f.read(), __file__, "exec"))
File "test_with.py", line 33, in <module>
test_with()
File "test_with.py", line 28, in test_with
raise Exception
Exception

證明了會先執行__enter__方法, 然後調用with內的邏輯, 最後執行__exit__做退出處理, 並且, 即使出現異常也能正常退出

filter的用法

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

1
2
3
4
5
6
7
8
9
#!/usr/bin/env python
# -*- coding: utf-8 -*-
lst = [1, 2, 3, 4, 5, 6]
# 所有奇數都會返回True, 偶數會返回False被過濾掉
print filter(lambda x: x % 2 != 0, lst)
#輸出結果
[1, 3, 5]

一行作判斷

當條件滿足時, 返回的爲等號後面的變量, 否則返回else後語句

1
2
3
4
5
6
lst = [1, 2, 3]
new_lst = lst[0] if lst is not None else None
print new_lst
# 打印結果
1

裝飾器之單例

使用裝飾器實現簡單的單例模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 單例裝飾器
def singleton(cls):
instances = dict() # 初始爲空
def _singleton(*args, **kwargs):
if cls not in instances: #如果不存在, 則創建並放入字典
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裝飾器

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

  • 普通成員函數, 其中第一個隱式參數爲對象
  • classmethod裝飾器, 類方法(給人感覺非常類似於OC中的類方法), 其中第一個隱式參數爲
  • staticmethod裝飾器, 沒有任何隱式參數. python中的靜態方法類似與C++中的靜態方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class A(object):
# 普通成員函數
def foo(self, x):
print "executing foo(%s, %s)" % (self, x)
@classmethod # 使用classmethod進行裝飾
def class_foo(cls, x):
print "executing class_foo(%s, %s)" % (cls, x)
@staticmethod # 使用staticmethod進行裝飾
def static_foo(x):
print "executing static_foo(%s)" % x
def test_three_method():
obj = A()
# 直接調用噗通的成員方法
obj.foo("para") # 此處obj對象作爲成員函數的隱式參數, 就是self
obj.class_foo("para") # 此處類作爲隱式參數被傳入, 就是cls
A.class_foo("para") #更直接的類方法調用
obj.static_foo("para") # 靜態方法並沒有任何隱式參數, 但是要通過對象或者類進行調用
A.static_foo("para")
if __name__ == '__main__':
test_three_method()
# 函數輸出
executing foo(<__main__.A object at 0x100ba4e10>, para)
executing class_foo(<class '__main__.A'>, para)
executing class_foo(<class '__main__.A'>, para)
executing static_foo(para)
executing static_foo(para)

property裝飾器

  • 定義私有類屬性

property與裝飾器結合實現屬性私有化(更簡單安全的實現get和set方法)

1
2
#python內建函數
property(fget=None, fset=None, fdel=None, doc=None)

fget是獲取屬性的值的函數,fset是設置屬性值的函數,fdel是刪除屬性的函數,doc是一個字符串(like a comment).從實現來看,這些參數都是可選的

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

1
2
3
4
5
6
7
8
9
10
11
12
13
class Student(object):
@property #相當於property.getter(score) 或者property(score)
def score(self):
return self._score
@score.setter #相當於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魔法

  • 通過yield和__iter__的結合, 我們可以把一個對象變成可迭代的
  • 通過__str__的重寫, 可以直接通過想要的形式打印對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/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++中仿函數(函數對象).

在stackoverflow給出了類似與partial的運行方式

1
2
3
4
5
6
7
def partial(func, *part_args):
def wrapper(*extra_args):
args = list(part_args)
args.extend(extra_args)
return func(*args)
return wrapper

利用用閉包的特性綁定預先綁定一些函數參數, 返回一個可調用的變量, 直到真正的調用執行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/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) # 事先綁定一個參數, fun成爲一個只需要一個參數的可調用變量
print fun(3) # 實現執行的即是sum(2, 3)
if __name__ == '__main__':
test_partial()
# 執行結果
5

神祕eval

eval我理解爲一種內嵌的python解釋器(這種解釋可能會有偏差), 會解釋字符串爲對應的代碼並執行, 並且將執行結果返回

看一下下面這個例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_first():
return 3
def test_second(num):
return num
action = { # 可以看做是一個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並根據action對應的動作執行
print res
if __name__ == '_

exec

  • exec在Python中會忽略返回值, 總是返回None, eval會返回執行代碼或語句的返回值
  • execeval在執行代碼時, 除了返回值其他行爲都相同
  • 在傳入字符串時, 會使用compile(source, '<string>', mode)編譯字節碼. mode的取值爲execeval
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/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() # 無法看到執行結果

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.

通過string類型的name, 返回對象的name屬性(方法)對應的值, 如果屬性不存在, 則返回默認值, 相當於object.name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 使用範例
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: # 沒有該屬性, 且沒有指定返回值的情況下
print "Method Error!"
if __name__ == '__main__':
test_getattr()
# 輸出結果
test attribute
test method

命令行處理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
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.:
if args:
parser.error('program takes no command-line arguments; '
'"%s" ignored.' % (args,))
# further process settings & args if necessary
return settings, args
def main(argv=None):
settings, args = process_command_line(argv)
# application code here, like:
# run(settings, args)
return 0 # success
if __name__ == '__main__':
status = main()
sys.exit(status)

讀寫csv文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 從csv中讀取文件, 基本和傳統文件讀取類似
import csv
with open('data.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
# 向csv文件寫入
import csv
with open( 'data.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(['name', 'address', 'age']) # 單行寫入
data = [
( 'xiaoming ','china','10'),
( 'Lily', 'USA', '12')]
writer.writerows(data) # 多行寫入

各種時間形式轉換

只發一張網上的圖, 然後差文檔就好了, 這個是記不住的

字符串格式化

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

1
2
3
>>> name = "andrew"
>>> "my name is {name}".format(name=name)
'my name is andrew'

參考鏈接

發佈了501 篇原創文章 · 獲贊 72 · 訪問量 139萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章