目錄
1、lambda
2、map
3、屬性函數-property
4、@staticmethod
正文
lambda()函數
舉個例子如下:
func=lambda x:x+1 print(func(1)) #2 print(func(2)) #3
#以上lambda等同於以下函數
def func(x): return(x+1)
可以這樣認爲,lambda作爲一個表達式,定義了一個匿名函數,上例的代碼x爲入口參數,x+1爲函數體。在這裏lambda簡化了函數定義的書寫形式。是代碼更爲簡潔,但是使用函數的定義方式更爲直觀,易理解。
Python中,也有幾個定義好的全局函數方便使用的,filter, map, reduce。
from functools import reduce foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] print (list(filter(lambda x: x % 3 == 0, foo))) #[18, 9, 24, 12, 27] print (list(map(lambda x: x * 2 + 10, foo))) #[14, 46, 28, 54, 44, 58, 26, 34, 64] print (reduce(lambda x, y: x + y, foo)) #139
上面例子中的map的作用,非常簡單清晰。但是,Python是否非要使用lambda才能做到這樣的簡潔程度呢?在對象遍歷處理方面,其實Python的for..in..if語法已經很強大,並且在易讀上勝過了lambda。
比如上面map的例子,可以寫成:print ([x * 2 + 10 for x in foo]) 非常的簡潔,易懂。
filter的例子可以寫成:print ([x for x in foo if x % 3 == 0]) 同樣也是比lambda的方式更容易理解。
map()函數
map()是 Python 內置的高階函數,它接收一個函數 f 和一個 list,並通過把函數 f 依次作用在 list 的每個元素上,得到一個新的 list 並返回。
例如,對於list [1, 2, 3, 4, 5, 6, 7, 8, 9]
如果希望把list的每個元素都作平方,就可以用map()函數:
因此,我們只需要傳入函數f(x)=x*x,就可以利用map()函數完成這個計算:
def f(x): return x*x print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) 輸出結果: [1, 4, 9, 10, 25, 36, 49, 64, 81]
注意:map()函數不改變原有的 list,而是返回一個新的 list。
利用map()函數,可以把一個 list 轉換爲另一個 list,只需要傳入轉換函數。
由於list包含的元素可以是任何類型,因此,map() 不僅僅可以處理只包含數值的 list,事實上它可以處理包含任意類型的 list,只要傳入的函數f可以處理這種數據類型。
任務
假設用戶輸入的英文名字不規範,沒有按照首字母大寫,後續字母小寫的規則,請利用map()函數,把一個list(包含若干不規範的英文名字)變成一個包含規範英文名字的list:
輸入:['adam', 'LISA', 'barT']
輸出:['Adam', 'Lisa', 'Bart']
def format_name(s): s1=s[0:1].upper()+s[1:].lower(); return s1; print map(format_name, ['adam', 'LISA', 'barT'])
map()函數是python內置的高階函數,對傳入的list的每一個元素進行映射,返回一個新的映射之後的list
屬性函數-property
Python中有一個被稱爲屬性函數(property)的小概念,它可以做一些有用的事情,比如能做以下幾點:
將類方法轉換爲只讀屬性
重新實現一個屬性的setter和getter方法
使用屬性函數的最簡單的方法之一是將它作爲一個方法的裝飾器來使用。這可以讓你將一個類方法轉變成一個類屬性。當我需要做某些值的合併時,我發現這很有用。其他想要獲取它作爲方法使用的人,發現在寫轉換函數時它很有用。讓我們來看一個簡單的例子:
class Person(object): """""" #---------------------------------------------------------------------- def __init__(self, first_name, last_name): """Constructor""" self.first_name = first_name self.last_name = last_name #---------------------------------------------------------------------- @property def full_name(self): """ Return the full name """ return "%s %s" % (self.first_name, self.last_name)
在上面的代碼中,我們創建了兩個類屬性:self.first_name和self.last_name。接下來,我們創建了一個full_name方法,它有一個@property裝飾器。這使我們能夠在Python解釋器會話中有如下的交互:
>>> person = Person("Mike", "Driscoll") >>> person.full_name 'Mike Driscoll' >>> person.first_name 'Mike'
正如你所看到的,因爲我們將方法變成了屬性,我們可以使用正常的點符號訪問它。但是,如果我們試圖將該屬性設爲其他值,我們會引發一個AttributeError錯誤。改變full_name屬性的唯一方法是間接這樣做:
>>> person.first_name = "Dan" >>> person.full_name 'Dan Driscoll'
staticmethod 靜態方法
python中的staticmethod 主要是方便將外部函數集成到類體中,美化代碼結構,重點在不需要類實例化的情況下調用方法
如果你去掉staticmethod,在方法中加self也可以通過實例化訪問方法也是可以集成代碼
1)先看看不使用staticmethod的代碼如何寫的
IND='ON' def checkind(): return (IND == 'ON') class Kls(object): def __init__(self,data): self.data = data def do_reset(self): if checkind(): print ('Reset done for:',self.data) def set_reset(self): if checkind(): # self.db='New db connection' print ('DB connection mode for:',self.data) ik1 = Kls(12) print (ik1.do_reset()) print (ik1.set_reset())
結果
Reset done for: 12 None DB connection mode for: 12 None
2)再看看使用staticmethod的代碼,用staticmethod包裝的方法可以內部調用,也可以通過類訪問或類實例化訪問
IND='ON' class Kls(object): def __init__(self,data): self.data = data @staticmethod def checkind(): return (IND == 'ON') def do_reset(self): if self.checkind(): print ('Reset done for:',self.data) def set_reset(self): if self.checkind(): # self.db='New db connection' print ('DB connection mode for:',self.data) ik1 = Kls(12) print (ik1.do_reset()) print (ik1.set_reset()) print (ik1.checkind()) print (Kls.checkind())
結果
Reset done for: 12 None DB connection mode for: 12 None True True