日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

20170204-py

發布時間:2025/1/21 编程问答 69 豆豆
生活随笔 收集整理的這篇文章主要介紹了 20170204-py 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

1.yield from

import asyncio@asyncio.coroutine def hello_f():for v in range(10):print('fff')@asyncio.coroutine def hello():print('Hello world!')r = yield from hello_f()print(r)print('Hello Again')loop = asyncio.get_event_loop()loop.run_until_complete(hello())loop.close()

執行結果:

Hello world! fff fff fff fff fff fff fff fff fff fff None Hello Again

?

def g(x):# yield from range(x)for i in range(x):yield il = list(g(5)) print(l)

?

2.yield

def libs():a = 0b = 1while True:a,b = b , a+byield afor each in libs():if each > 100:breakprint(each,end=' ')

執行結果:

1 1 2 3 5 8 13 21 34 55 89

3.Python中的and or not

在Python中,對于邏輯運算符and 、or、 not 需要注意一下:

and :x and y 返回的結果是決定表達式結果的值。如果 x 為真,則 y 決定結果,返回 y ;如果 x 為假,x 決定了結果為假,返回 x。

or :x or y ?跟 and 一樣都是返回決定表達式結果的值。

not : 返回表達式結果的“相反的值”。如果表達式結果為真,則返回false;如果表達式結果為假,則返回true。

a = [i for i in range(100) if not(i%2) and (i % 3)] a = [i for i in range(100) if (i %2 == 0) and (i %3 != 0)]print(a)b = {i: i%2 == 0 for i in range(10)} print(b)print(2 %2 == 1)

執行結果:

[2, 4, 8, 10, 14, 16, 20, 22, 26, 28, 32, 34, 38, 40, 44, 46, 50, 52, 56, 58, 62, 64, 68, 70, 74, 76, 80, 82, 86, 88, 92, 94, 98] {0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False} False

?

4.生成器

e = (i for i in range(10))print(e) print(next(e)) print(next(e))

執行結果:

<generator object <genexpr> at 0x10137f938> 0 1

5.模塊倒入

TempeartureConversion.py

def c2f(cel):fah = cel * 1.8 + 32return fahdef f2c(fah):cel = (fah-32) / 1.8return cel

?

calc.py

from TempeartureConversion import c2fimport TempeartureConversion as tcprint('32 = %02f' % c2f(32))print('89.6 = %02f' % tc.f2c(89.6))

執行結果:

32 = 89.600000 89.6 = 32.000000

?

6.global

在python中,變量不需要先聲明,直接使用即可,那我們怎么知道用的是局部變量還是全局變量呢?

首先:python使用的變量,在默認情況下一定是用局部變量。

其次:python如果想使用作用域之外的全局變量,則需要加global前綴。

舉例說明,不用global的情況:

a = 5 def test(): a = 1 print 'In test func: a = %d' % a test() print 'Global a = %d' % a

程序執行結果為:

In test func: a = 1 Global a = 5

可以看出,不加global的時候,在函數內部是改不了外面的全局變量的(list類型例外)。

下面是使用global前綴的情況:

a = 5 def test(): global a #此處聲明,告訴執行引擎:我要用全局變量a,不要整成局部的了! a = 1 print 'In test func: a = %d' % a test() print 'Global a = %d' % a

執行結果:

In test func: a = 1 Global a = 1

可以看出,在函數內部成功的修改了全局變量的數值。
?

?

事實上,網絡上很多文章推崇另外的一種方法來使用全局變量:使用單獨的global文件。

?

方法如下:

1. 在同一個文件夾下,新建2個文件: myglobal.py test.py

2.?myglobal.py中放置全局變量,內容示例如下:

a = 0 b = 1 c = 2 d = 3

?

3. test.py中是測試代碼,其中可以使用全局變量

import myglobal def test(): myglobal.a = 100 print 'myglobal a = %d' % myglobal.a test() print 'after test, myglobal a = %d' % myglobal.a

執行test.py的結果如下:

myglobal a = 0 after test, myglobal a = 100

OK,同樣成功修改了全局變量(這個說法不準確,但姑且就這么叫吧)。
?

?

?

在實際使用中,兩種方法各有優勢,通常我們大多數時候只是用python寫小功能的腳本,此時用global關鍵字就夠了。

如果寫比較大的功能應用時,用后一種方法可以使得全局變量的管理更為方便。

?

7.with as

class Sample:def __enter__(self):print "In __enter__()"return "Foo"def __exit__(self, type, value, trace):print "In __exit__()"def get_sample():return Sample()with get_sample() as sample:print "sample:", sample

執行結果:

In __enter__() sample: Foo In __exit__()

1. __enter__()方法被執行
2. __enter__()方法返回的值 - 這個例子中是"Foo",賦值給變量'sample'
3. 執行代碼塊,打印變量"sample"的值為 "Foo"
4. __exit__()方法被調用with真正強大之處是它可以處理異常。可能你已經注意到Sample類的__exit__方法有三個參數- val, type 和 trace。這些參數在異常處理中相當有用。我們來改一下代碼,看看具體如何工作的。

?

8.裝飾器

請編寫一個decorator,能在函數調用的前后打印出'begin call'和'end call'的日志。

import functoolsdef log(func):def beforfunc(func):print('beging call')def afterfun(func):print('after call')@functools.wraps(func)def wrapper(*args,**kw):beforfunc(func)f = func(*args,**kw)afterfun(func)return freturn wrapper@log def now():print('aa')now()

9.async/await

用asyncio提供的@asyncio.coroutine可以把一個generator標記為coroutine類型,然后在coroutine內部用yield from調用另一個coroutine實現異步操作。

為了簡化并更好地標識異步IO,從Python 3.5開始引入了新的語法async和await,可以讓coroutine的代碼更簡潔易讀。

請注意,async和await是針對coroutine的新語法,要使用新的語法,只需要做兩步簡單的替換:

  • 把@asyncio.coroutine替換為async;
  • 把yield from替換為await。
  • 讓我們對比一下上一節的代碼:

    @asyncio.coroutine def hello():print("Hello world!")r = yield from asyncio.sleep(1)print("Hello again!")

    用新語法重新編寫如下:

    async def hello():print("Hello world!")r = await asyncio.sleep(1)print("Hello again!")

    剩下的代碼保持不變。

    小結

    Python從3.5版本開始為asyncio提供了async和await的新語法;

    注意新語法只能用在Python 3.5以及后續版本,如果使用3.4版本,則仍需使用上一節的方案。

    ?

    10.callable

    中文說明:檢查對象object是否可調用。如果返回True,object仍然可能調用失敗;但如果返回False,調用對象ojbect絕對不會成功。

    注意:類是可調用的,而類的實例實現了__call__()方法才可調用。

    版本:該函數在python2.x版本中都可用。但是在python3.0版本中被移除,而在python3.2以后版本中被重新添加。

    ?

    英文說明:Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__() method.

    11.函數參數

    POSITIONAL_ONLY;位置參數

    VAR_POSITIONAL:可變參數

    POSITIONAL_OR_KEYWORD:位置參數或命名關鍵字參數

    VAR_KEYWORD:命名關鍵字參數

    KEYWORD_ONLY:關鍵字參數

    命名關鍵字的一個用法:

    #命名關鍵字的一個用法 configs = {'db': {'host': '127.0.0.1','port': 3306,'user': 'root','password': 'root','db': 'awesome'},'session': {'secret': 'AwEsOmE'} }def test(**args):print(args)test(**configs)

    運行結果:注意兩個星號

    /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/aslan/python_learn/0203/webapp/ios/t.py {'session': {'secret': 'AwEsOmE'}, 'db': {'port': 3306, 'password': 'root', 'host': '127.0.0.1', 'db': 'awesome', 'user': 'root'}}Process finished with exit code 0

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    ?

    轉載于:https://my.oschina.net/aslanjia/blog/831348

    總結

    以上是生活随笔為你收集整理的20170204-py的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。