17個Python奇技淫巧分享
顯示有限的介面到外部
當發布python第三方package時,並不希望程式碼中所有的函數或class可以被外部import,在init.py中加入all屬性,list#可以填入可以import的類別或函數名, 可以起到限制的import的作用, 防止外部import其他函數或類別。
#!/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之後的表達式, 表達式傳回一個上下文管理物件。
# 常见with使用场景 with open("test.txt", "r") as my_file: # 注意, 是enter()方法的返回值赋值给了my_file, for line in my_file: print line
詳細原理可以看這篇文章, 淺談 Python 的 with 語句。
知道具體原理,我們可以自訂支援上下文管理協定的類,類別中實作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 # 返回对象给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()
執行結果如下:
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(filef.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</module></module>
證明了會先執行enter方法, 然後呼叫with內的邏輯, 最後執行exit做退出處理, 並且, 即使出現異常也能正常退出
filter的用法
相對filter而言, map和reduce使用的會更頻繁一些, filter正如其名字, 依照某種規則過濾掉一些元素。
#!/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後語句。
lst = [1, 2, 3] new_lst = lst[0] if lst is not None else None print new_lst # 打印结果 1
裝飾器之單例
使用裝飾器實作簡單的單例模式
# 单例装饰器 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
static method裝飾器
類別中兩種常用的裝飾, 先區分一下他們:
普通成員函數, 其中第一個隱式參數為物件
classmethod裝飾器, 類別方法(給人感覺非常類似於OC中的類別方法), 其中第一個隱式參數為類別
staticmethod裝飾器, 沒有任何隱含參數. python中的靜態方法類似與C++中的靜態方法
#!/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>, para) executing class_foo(<class>, para) executing class_foo(<class>, para) executing static_foo(para) executing static_foo(para)</class></class></main.a>
property裝飾器
定義私有類別屬性
將property與裝飾器結合實作屬性私有化(更簡單安全的實作get和set方法)。
#python内建函数 property(fget=None, fset=None, fdel=None, doc=None)
fget是取得屬性的值的函數,fset是設定屬性值的函數,fdel是刪除屬性的函數,doc是一個字串(像註解一樣)。從實作來看,這些參數都是可選的。
property有三個方法getter(), setter()和delete() 來指定fget, fset和fdel。 這表示以下這行:
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 100: raise ValueError('score must between 0 ~ 100!') self._score = value
iter魔法
透過yield和iter的結合,我們可以把一個物件變成可迭代的
透過str的重寫, 可以直接透過想要的形式列印物件
#!/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的運作方式:
def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper
利用用閉包的特性綁定預先綁定一些函數參數,傳回一個可呼叫的變量, 直到真正的呼叫執行:
#!/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解释器(这种解释可能会有偏差), 会解释字符串为对应的代码并执行, 并且将执行结果返回。
看一下下面这个例子:
#!/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会返回执行代码或语句的返回值
exec和eval在执行代码时, 除了返回值其他行为都相同
在传入字符串时, 会使用compile(source, ‘string>’, mode)编译字节码。 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() # 无法看到执行结果
getattr
getattr(object, name[, default])返回对象的命名属性,属性名必须是字符串。如果字符串是对象的属性名之一,结果就是该属性的值。例如, getattr(x, ‘foobar’) 等价于 x.foobar。 如果属性名不存在,如果有默认值则返回默认值,否则触发 AttributeError 。
# 使用范例 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
命令行处理
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文件
# 从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) # 多行写入
各种时间形式转换
只发一张网上的图, 然后查文档就好了, 这个是记不住的
字符串格式化
一个非常好用, 很多人又不知道的功能:
>>> name = "andrew" >>> "my name is {name}".format(name=name) 'my name is andrew'
以上是17個Python奇技淫巧分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

在 Visual Studio Code(VSCode)中編寫代碼簡單易行,只需安裝 VSCode、創建項目、選擇語言、創建文件、編寫代碼、保存並運行即可。 VSCode 的優點包括跨平台、免費開源、強大功能、擴展豐富,以及輕量快速。

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。
