python修飾器函數(shù)的簡單介紹

什么是 NUMBA?

藍海大腦深度學習高性能液冷服務(wù)器研究人員表示:

讓客戶滿意是我們工作的目標,不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價值的長期合作伙伴,公司提供的服務(wù)項目有:申請域名、網(wǎng)站空間、營銷軟件、網(wǎng)站建設(shè)、太和網(wǎng)站維護、網(wǎng)站推廣。

為了提高執(zhí)行速度,Numba 會在執(zhí)行前立即將 Python 字節(jié)代碼轉(zhuǎn)換為機器代碼。

Numba 可用于使用可調(diào)用的 Python 對象(稱為修飾器)來優(yōu)化 CPU 和 GPU 功能。修飾器是一個函數(shù),它將另一個函數(shù)作為輸入,進行修改,并將修改后的函數(shù)返回給用戶。這種模組化可減少編程時間,并提高 Python 的可擴展性。

Numba 還可與 NumPy 結(jié)合使用,后者是一個復(fù)雜數(shù)學運算的開源 Python 庫,專為處理統(tǒng)計數(shù)據(jù)而設(shè)計。調(diào)用修飾器時,Numa 將 Python 和/或 NumPy 代碼的子集轉(zhuǎn)換為針對環(huán)境自動優(yōu)化的字節(jié)碼。它使用 LLVM,這是一個面向 API 的開源庫,用于以編程方式創(chuàng)建機器原生代碼。Numba 針對各種 CPU 和 GPU 配置,提供了多種快速并行化 Python 代碼的選項,有時僅需一條命令即可。與 NumPy 結(jié)合使用時,Numba 會為不同的數(shù)組數(shù)據(jù)類型和布局生成專用代碼,進而優(yōu)化性能。

如何在Python Flask框架中運行重復(fù)任務(wù)

Flask是一個使用Python編寫的輕量級Web應(yīng)用框架,憑借更靈活、輕便、安全且容易上手的特性,成為企業(yè)常用的Python框架之一。在完成Web前端、Linux以及MySQL相關(guān)的課程之后,專業(yè)的杭州Python學習班都會講解Flask框架知識,以下是整理的相關(guān)知識點。

Flask是一個基于Python開發(fā)并且依賴jinja2模板和Werkzeug WSGI服務(wù)的一個微型框架,對于Werkzeug本質(zhì)是Socket服務(wù)端,其用于接收http請求并對請求進行預(yù)處理,然后觸發(fā)Flask框架。開發(fā)人員基于Flask框架提供的功能對請求進行相應(yīng)的處理,并返回給用戶,如果要返回給用戶復(fù)雜的內(nèi)容時,需要借助jinja2模板來實現(xiàn)對模板的處理,即:將模板和數(shù)據(jù)進行渲染,將渲染后的字符串返回給用戶瀏覽器。

默認情況下,F(xiàn)lask不包含數(shù)據(jù)庫抽象層、表單驗證,或是其它任何已有多種庫可以勝任的功能。然而,F(xiàn)lask支持用擴展來給應(yīng)用添加這些功能,如同是Flask本身實現(xiàn)的一樣。眾多的擴展提供了數(shù)據(jù)庫集成、表單驗證、上傳處理、各種各樣的開放認證技術(shù)等功能。

Flask框架的特點:

1)Flask自由、靈活,可擴展性強,第三方庫的選擇面廣,開發(fā)時可以結(jié)合自己最喜歡用的輪子,也能結(jié)合最流行最強大的Python庫;

2)入門簡單,即便沒有多少web開發(fā)經(jīng)驗,也能很快做出網(wǎng)站;

3)非常適用于小型網(wǎng)站;

4)非常適用于開發(fā)Web服務(wù)的API;

5)開發(fā)大型網(wǎng)站無壓力,但代碼架構(gòu)需要自己設(shè)計,開發(fā)成本取決于開發(fā)者的能力和經(jīng)驗。

Flask框架運行解釋

1.app = Flask(__name__)

創(chuàng)建Flask對象app,F(xiàn)lask類的構(gòu)造函數(shù)只有一個必須指定的參數(shù),即程序主模塊或包的名字。在大多數(shù)程序中,Python的__name__變量就是所需要的值。

2.@app.route('/')

web瀏覽器把請求發(fā)送給Web服務(wù)器,Web服務(wù)器再把請求發(fā)送給Flask程序?qū)嵗?。程序?qū)嵗枰缹γ總€URL請求運行哪些代碼,所以保存了一個URL到Python函數(shù)的映射關(guān)系。處理URL和函數(shù)之間的關(guān)系的程序稱為路由。在Flask程序中定義路由的最簡便方式,是使用程序?qū)嵗峁┑腶pp.route修飾器,把修飾的函數(shù)注冊為路由。route()裝飾器告訴 Flask什么樣的URL 能觸發(fā)我們的函數(shù)。這和Java中的注釋有異曲同工之妙。修飾器是Python語言的標準特性,可以使用不同的方式修改函數(shù)的行為。慣常用法是使用修飾器把函數(shù)注冊為事件的處理程序。

3.def index():函數(shù)

index()函數(shù)放在@app.route('/')后面,所以就是把index()函數(shù)注冊為路由。如果部署程序的服務(wù)器域名為,在瀏覽器中訪問后,會觸發(fā)服務(wù)器執(zhí)行index()函數(shù)。

4.@app.route('/user/')

同@app.route('/'),如果部署程序的服務(wù)器域名為,在瀏覽器中訪問后,會觸發(fā)服務(wù)器執(zhí)行下方修飾函數(shù)。

5.app.run(debug=True)

程序?qū)嵗胷un方法啟動Flask繼承Web服務(wù)器。

6.if __name__ == '__main__'

當Python解釋器,讀py文件,它會執(zhí)行它發(fā)現(xiàn)的所有代碼。在執(zhí)行代碼之前,它會定義一些變量。例如,如果這個py文件就是主程序,它會設(shè)置__name__變量為"__main__"。如果這個py被引入到別的模塊,__name__會被設(shè)置為該模塊的名字。

python函數(shù)的幾種參數(shù)類型

#Python 2.5 #這個可以用修飾器來完成 #但是一般不會限制參數(shù)類型 #給你個思路: def argfilter(*types): def deco(func): #這是修飾器 def newfunc(*args): #新的函數(shù) if len(types)==len(args): correct = True for i in range(len(args)): if not isinstance(args[i], types[i]): #判斷類型 correct = False if correct: return func(*args) #返回原函數(shù)值 else: raise TypeError else: raise TypeError return newfunc #由修飾器返回新的函數(shù) return deco #返回作為修飾器的函數(shù) @argfilter(int, str) #指定參數(shù)類型 def func(i, s): #定義被修飾的函數(shù) print i, s #之后你想限制類型的話, 就這樣: #@argfilter(第一個參數(shù)的類名, 第二個參數(shù)的類名, ..., 第N個參數(shù)的類名) #def yourfunc(第一個參數(shù), 第一個參數(shù), ..., 第N個參數(shù)): # ... # #相當于: #def yourfunc(第一個參數(shù), 第一個參數(shù), ..., 第N個參數(shù)): # ... #yourfunc = argfilter(第一個參數(shù)的類名, 第二個參數(shù)的類名, ..., 第N個參數(shù)的類名)(yourfunc)

python中修飾器是什么?

就是一個callable object。 它使python編程更加容易。

例如:

@dec

def A(args):

pass

它就等價于dec(A). 當然還有帶參數(shù)的decorator。我就不舉例了。

python文檔里有這樣一句話。

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion.

大概就是說函數(shù)的定義可以用多個decorator。decorator就在函數(shù)定義時用函數(shù)作為參數(shù)調(diào)用,然后返回一個可調(diào)用對象。 所以寫decorator的時候一定要返回一個可調(diào)用對象。

不知道你明白沒。

python中怎么設(shè)定函數(shù)形參的類型

直接寫個名字就行。python的一切默認都是對象,參數(shù)沒使用前,是沒有類型的。甚至函數(shù)寫不寫行參都無所謂。

如何正確地使用Python的屬性和描述符

關(guān)于@property裝飾器

在Python中我們使用@property裝飾器來把對函數(shù)的調(diào)用偽裝成對屬性的訪問。

那么為什么要這樣做呢?因為@property讓我們將自定義的代碼同變量的訪問/設(shè)定聯(lián)系在了一起,同時為你的類保持一個簡單的訪問屬性的接口。

舉個栗子,假如我們有一個需要表示電影的類:

1

2

3

4

5

6

7

8

class Movie(object):

def __init__(self, title, description, score, ticket):

self.title = title

self.description = description

self.score = scroe

self.ticket = ticket

你開始在項目的其他地方使用這個類,但是之后你意識到:如果不小心給電影打了負分怎么辦?你覺得這是錯誤的行為,希望Movie類可以阻止這個錯誤。 你首先想到的辦法是將Movie類修改為這樣:

Python

1

2

3

4

5

6

7

8

class Movie(object):

def __init__(self, title, description, score, ticket):

self.title = title

self.description = description

self.ticket = ticket

if score 0:

raise ValueError("Negative value not allowed:{}".format(score))

self.score = scroe

但這行不通。因為其他部分的代碼都是直接通過Movie.score來賦值的。這個新修改的類只會在__init__方法中捕獲錯誤的數(shù)據(jù),但對于已經(jīng)存在的類實例就無能為力了。如果有人試著運行m.scrore= -100,那么誰也沒法阻止。那該怎么辦?

Python的property解決了這個問題。

我們可以這樣做

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

class Movie(object):

def __init__(self, title, description, score):

self.title = title

self.description = description

self.score = score

self.ticket = ticket

@property

def score(self):

return self.__score

@score.setter

def score(self, score):

if score 0:

raise ValueError("Negative value not allowed:{}".format(score))

self.__score = score

@score.deleter

def score(self):

raise AttributeError("Can not delete score")

這樣在任何地方修改score都會檢測它是否小于0。

property的不足

對property來說,最大的缺點就是它們不能重復(fù)使用。舉個例子,假設(shè)你想為ticket字段也添加非負檢查。下面是修改過的新類:

Python

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

class Movie(object):

def __init__(self, title, description, score, ticket):

self.title = title

self.description = description

self.score = score

self.ticket = ticket

@property

def score(self):

return self.__score

@score.setter

def score(self, score):

if score 0:

raise ValueError("Negative value not allowed:{}".format(score))

self.__score = score

@score.deleter

def score(self):

raise AttributeError("Can not delete score")

@property

def ticket(self):

return self.__ticket

@ticket.setter

def ticket(self, ticket):

if ticket 0:

raise ValueError("Negative value not allowed:{}".format(ticket))

self.__ticket = ticket

@ticket.deleter

def ticket(self):

raise AttributeError("Can not delete ticket")

可以看到代碼增加了不少,但重復(fù)的邏輯也出現(xiàn)了不少。雖然property可以讓類從外部看起來接口整潔漂亮,但是卻做不到內(nèi)部同樣整潔漂亮。

描述符登場

什么是描述符?

一般來說,描述符是一個具有綁定行為的對象屬性,其屬性的訪問被描述符協(xié)議方法覆寫。這些方法是__get__()、__set__()和__delete__(),一個對象中只要包含了這三個方法中的至少一個就稱它為描述符。

描述符有什么作用?

The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, a.x has a lookup chain starting witha.__dict__[‘x’], then type(a).__dict__[‘x’], and continuing through the base classes of type(a) excluding metaclasses. If the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined.—–摘自官方文檔

簡單的說描述符會改變一個屬性的基本的獲取、設(shè)置和刪除方式。

先看如何用描述符來解決上面 property邏輯重復(fù)的問題。

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class Integer(object):

def __init__(self, name):

self.name = name

def __get__(self, instance, owner):

return instance.__dict__[self.name]

def __set__(self, instance, value):

if value 0:

raise ValueError("Negative value not allowed")

instance.__dict__[self.name] = value

class Movie(object):

score = Integer('score')

ticket = Integer('ticket')

因為描述符優(yōu)先級高并且會改變默認的get、set行為,這樣一來,當我們訪問或者設(shè)置Movie().score的時候都會受到描述符Integer的限制。

不過我們也總不能用下面這樣的方式來創(chuàng)建實例。

a = Movie()

a.score = 1

a.ticket = 2

a.title = ‘test’

a.descript = ‘…’

這樣太生硬了,所以我們還缺一個構(gòu)造函數(shù)。

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

class Integer(object):

def __init__(self, name):

self.name = name

def __get__(self, instance, owner):

if instance is None:

return self

return instance.__dict__[self.name]

def __set__(self, instance, value):

if value 0:

raise ValueError('Negative value not allowed')

instance.__dict__[self.name] = value

class Movie(object):

score = Integer('score')

ticket = Integer('ticket')

def __init__(self, title, description, score, ticket):

self.title = title

self.description = description

self.score = score

self.ticket = ticket

這樣在獲取、設(shè)置和刪除score和ticket的時候都會進入Integer的__get__、__set__,從而減少了重復(fù)的邏輯。

現(xiàn)在雖然問題得到了解決,但是你可能會好奇這個描述符到底是如何工作的。具體來說,在__init__函數(shù)里訪問的是自己的self.score和self.ticket,怎么和類屬性score和ticket關(guān)聯(lián)起來的?

描述符如何工作

看官方的說明

If an object defines both __get__() and __set__(), it is considered a data descriptor. Descriptors that only define __get__() are called non-data descriptors (they are typically used for methods but other uses are possible).

Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.

The important points to remember are:

descriptors are invoked by the __getattribute__() method

overriding __getattribute__() prevents automatic descriptor calls

object.__getattribute__() and type.__getattribute__() make different calls to __get__().

data descriptors always override instance dictionaries.

non-data descriptors may be overridden by instance dictionaries.

類調(diào)用__getattribute__()的時候大概是下面這樣子:

1

2

3

4

5

6

7

def __getattribute__(self, key):

"Emulate type_getattro() in Objects/typeobject.c"

v = object.__getattribute__(self, key)

if hasattr(v, '__get__'):

return v.__get__(None, self)

return v

下面是摘自國外一篇博客上的內(nèi)容。

Given a Class “C” and an Instance “c” where “c = C(…)”, calling “c.name” means looking up an Attribute “name” on the Instance “c” like this:

Get the Class from Instance

Call the Class’s special method getattribute__. All objects have a default __getattribute

Inside getattribute

Get the Class’s mro as ClassParents

For each ClassParent in ClassParents

If the Attribute is in the ClassParent’s dict

If is a data descriptor

Return the result from calling the data descriptor’s special method __get__()

Break the for each (do not continue searching the same Attribute any further)

If the Attribute is in Instance’s dict

Return the value as it is (even if the value is a data descriptor)

For each ClassParent in ClassParents

If the Attribute is in the ClassParent’s dict

If is a non-data descriptor

Return the result from calling the non-data descriptor’s special method __get__()

If it is NOT a descriptor

Return the value

If Class has the special method getattr

Return the result from calling the Class’s special method__getattr__.

我對上面的理解是,訪問一個實例的屬性的時候是先遍歷它和它的父類,尋找它們的__dict__里是否有同名的data descriptor如果有,就用這個data descriptor代理該屬性,如果沒有再尋找該實例自身的__dict__,如果有就返回。任然沒有再查找它和它父類里的non-data descriptor,最后查找是否有__getattr__

描述符的應(yīng)用場景

python的property、classmethod修飾器本身也是一個描述符,甚至普通的函數(shù)也是描述符(non-data discriptor)

django model和SQLAlchemy里也有描述符的應(yīng)用

Python

1

2

3

4

5

6

7

8

9

10

11

12

class User(db.Model):

id = db.Column(db.Integer, primary_key=True)

username = db.Column(db.String(80), unique=True)

email = db.Column(db.String(120), unique=True)

def __init__(self, username, email):

self.username = username

self.email = email

def __repr__(self):

return 'User %r' % self.username

后記

只有當確實需要在訪問屬性的時候完成一些額外的處理任務(wù)時,才應(yīng)該使用property。不然代碼反而會變得更加啰嗦,而且這樣會讓程序變慢很多。

網(wǎng)站題目:python修飾器函數(shù)的簡單介紹
地址分享:http://muchs.cn/article14/docdhge.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、外貿(mào)建站、網(wǎng)站改版App開發(fā)、做網(wǎng)站、虛擬主機

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設(shè)計