国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

一波神奇的Python語句、函數(shù)與方法的使用技巧總結(jié)

2019-11-25 17:01:11
字體:
供稿:網(wǎng)友

顯示有限的接口到外部
當發(fā)布python第三方package時,并不希望代碼中所有的函數(shù)或者class可以被外部import,在__init__.py中添加__all__屬性,該list中填寫可以import的類或者函數(shù)名, 可以起到限制的import的作用, 防止外部import其他函數(shù)或者類。

#!/usr/bin/env python# -*- coding: utf-8 -*-from base import APIBasefrom client import Clientfrom decorator import interface, export, streamfrom server import Serverfrom storage import Storagefrom 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語句需要支持上下文管理協(xié)議的對象, 上下文管理協(xié)議包含__enter__和__exit__兩個方法。 with語句建立運行時上下文需要通過這兩個方法執(zhí)行進入和退出操作。

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

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

知道具體原理,我們可以自定義支持上下文管理協(xié)議的類,類中實現(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 # 返回對象給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 Falsedef 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__ methodrunning my_with__exit__ methodExited without Exception------分割線-----__init__ method__enter__ methodrunning before Exception__exit__ methodExited with ExceptionTraceback (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 ExceptionException

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

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

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

一行作判斷
當條件滿足時, 返回的為等號后面的變量, 否則返回else后語句。

lst = [1, 2, 3]new_lst = lst[0] if lst is not None else Noneprint new_lst# 打印結(jié)果1

裝飾器之單例
使用裝飾器實現(xià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@singletonclass Test(object):  passif __name__ == '__main__':  t1 = Test()  t2 = Test()  # 兩者具有相同的地址  print t1, t2

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

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

  • classmethod裝飾器, 類方法(給人感覺非常類似于OC中的類方法), 其中第一個隱式參數(shù)為類
  • staticmethod裝飾器, 沒有任何隱式參數(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進行裝飾  def class_foo(cls, x):    print "executing class_foo(%s, %s)" % (cls, x)  @staticmethod # 使用staticmethod進行裝飾  def static_foo(x):    print "executing static_foo(%s)" % xdef test_three_method():  obj = A()  # 直接調(diào)用噗通的成員方法  obj.foo("para") # 此處obj對象作為成員函數(shù)的隱式參數(shù), 就是self  obj.class_foo("para") # 此處類作為隱式參數(shù)被傳入, 就是cls  A.class_foo("para") #更直接的類方法調(diào)用  obj.static_foo("para") # 靜態(tài)方法并沒有任何隱式參數(shù), 但是要通過對象或者類進行調(diào)用  A.static_foo("para")if __name__ == '__main__':  test_three_method()  # 函數(shù)輸出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與裝飾器結(jié)合實現(xiàn)屬性私有化(更簡單安全的實現(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是一個字符串(像注釋一樣)。從實現(xiàn)來看,這些參數(shù)都是可選的。

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 < 0 or value > 100:      raise ValueError('score must between 0 ~ 100!')    self._score = value

iter魔法
通過yield和__iter__的結(jié)合,我們可以把一個對象變成可迭代的
通過__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 objif __name__ == '__main__':  test_iter()

神奇partial
partial使用上很像C++中仿函數(shù)(函數(shù)對象)。

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

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ù),返回一個可調(diào)用的變量, 直到真正的調(diào)用執(zhí)行:

#!/usr/bin/env python# -*- coding: utf-8 -*-from functools import partialdef sum(a, b):  return a + bdef test_partial():  fun = partial(sum, 2)  # 事先綁定一個參數(shù), fun成為一個只需要一個參數(shù)的可調(diào)用變量  print fun(3) # 實現(xiàn)執(zhí)行的即是sum(2, 3)if __name__ == '__main__':  test_partial()  # 執(zhí)行結(jié)果5

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

看一下下面這個例子:

#!/usr/bin/env python# -*- coding: utf-8 -*-def test_first():  return 3def test_second(num):  return numaction = { # 可以看做是一個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對應(yīng)的動作執(zhí)行  print resif __name__ == '_

exec
exec在Python中會忽略返回值, 總是返回None, eval會返回執(zhí)行代碼或語句的返回值
exec和eval在執(zhí)行代碼時, 除了返回值其他行為都相同
在傳入字符串時, 會使用compile(source, '<string>', 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 actionif __name__ == '__main__':  test_exec() # 無法看到執(zhí)行結(jié)果

getattr
getattr(object, name[, default])返回對象的命名屬性,屬性名必須是字符串。如果字符串是對象的屬性名之一,結(jié)果就是該屬性的值。例如, getattr(x, ‘foobar') 等價于 x.foobar。 如果屬性名不存在,如果有默認值則返回默認值,否則觸發(fā) 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()  # 輸出結(jié)果test attributetest 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, argsdef main(argv=None):  settings, args = process_command_line(argv)  # application code here, like:  # run(settings, args)  return 0    # successif __name__ == '__main__':  status = main()  sys.exit(status)

讀寫csv文件

# 從csv中讀取文件, 基本和傳統(tǒng)文件讀取類似import csvwith open('data.csv', 'rb') as f:  reader = csv.reader(f)  for row in reader:    print row# 向csv文件寫入import csvwith 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) # 多行寫入
各種時間形式轉(zhuǎn)換
只發(fā)一張網(wǎng)上的圖, 然后查文檔就好了, 這個是記不住的

2015128155735251.jpg (739×549)

字符串格式化
一個非常好用, 很多人又不知道的功能:

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 苏尼特左旗| 聂拉木县| 称多县| 内丘县| 万荣县| 封丘县| 峡江县| 九江市| 临泉县| 屏东市| 六安市| 延吉市| 磐安县| 沙洋县| 河北省| 镇康县| 彩票| 五莲县| 雷州市| 嘉祥县| 河北区| 浪卡子县| 临湘市| 集贤县| 郓城县| 天峻县| 江西省| 济南市| 始兴县| 阿坝县| 修文县| 三原县| 会东县| 治县。| 盐边县| 常州市| 即墨市| 颍上县| 汉川市| 德化县| 衡水市|