Python 函數(shù) 類 語法糖

原文作者:zzir

Python 語法糖

\壳鹤,換行連接
s = ''
s += 'a' + \
     'b' + \
     'c'
n = 1 + 2 + \
3
# 6
while魔吐,for 循環(huán)外的 else

如果 while 循環(huán)正常結(jié)束(沒有break退出)就會執(zhí)行else弯汰。

num = [1,2,3,4]
mark = 0
while mark < len(num):
    n = num[mark]
    if n % 2 == 0:
        print(n)
        # break
    mark += 1
else: print("done”)

zip() 并行迭代
a = [1,2,3]
b = ['one','two','three']
list(zip(a,b))
# [(1, 'one'), (2, 'two'), (3, 'three’)]

列表推導(dǎo)式
x = [num for num in range(6)]
# [0, 1, 2, 3, 4, 5]
y = [num for num in range(6) if num % 2 == 0]
# [0, 2, 4]

# 多層嵌套
rows = range(1,4)
cols = range(1,3)
for i in rows:
    for j in cols:
        print(i,j)
# 同
rows = range(1,4)
cols = range(1,3)
x = [(i,j) for i in rows for j in cols]
字典推導(dǎo)式

{ key_exp : value_exp fro expression in iterable }

#查詢每個字母出現(xiàn)的次數(shù)。
strs = 'Hello World'
s = { k : strs.count(k) for k in set(strs) }
集合推導(dǎo)式

{expression for expression in iterable }

元組沒有推導(dǎo)式

本以為元組推導(dǎo)式是列表推導(dǎo)式改成括號窗宦,后來發(fā)現(xiàn)那個 生成器推導(dǎo)式赦颇。

生成器推導(dǎo)式
>>> num = ( x for x in range(5) )
>>> num
...:<generator object <genexpr> at 0x7f50926758e0>

函數(shù)

函數(shù)關(guān)鍵字參數(shù),默認(rèn)參數(shù)值
def do(a=0,b,c)
    return (a,b,c)

do(a=1,b=3,c=2)

函數(shù)默認(rèn)參數(shù)值在函數(shù)定義時已經(jīng)計算出來赴涵,而不是在程序運行時媒怯。
列表字典等可變數(shù)據(jù)類型不可以作為默認(rèn)參數(shù)值。

def buygy(arg, result=[]):
    result.append(arg)
    print(result)

changed:

def nobuygy(arg, result=None):
    if result == None:
        result = []
    result.append(arg)
    print(result)
# or
def nobuygy2(arg):
    result = []
    result.append(arg)
    print(result)
*args 收集位置參數(shù)
def do(*args):
    print(args)
do(1,2,3)
(1,2,3,'d’)
**kwargs 收集關(guān)鍵字參數(shù)
def do(**kwargs):
  print(kwargs)
do(a=1,b=2,c='la')
# {'c': 'la', 'a': 1, 'b': 2}
lamba 匿名函數(shù)
a = lambda x: x*x
a(4)
# 16
生成器

生成器是用來創(chuàng)建Python序列的一個對象髓窜∩劝可以用它迭代序列而不需要在內(nèi)存中創(chuàng)建和存儲整個序列欺殿。
通常,生成器是為迭代器產(chǎn)生數(shù)據(jù)的鳖敷。

生成器函數(shù)函數(shù)和普通函數(shù)類似脖苏,返回值使用 yield 而不是 return 。

def my_range(first=0,last=10,step=1):
    number = first
    while number < last:
        yield number
        number += step

>>> my_range()
... <generator object my_range at 0x7f02ea0a2bf8>
裝飾器

有時需要在不改變源代碼的情況下修改已經(jīng)存在的函數(shù)定踱。
裝飾器實質(zhì)上是一個函數(shù)帆阳,它把函數(shù)作為參數(shù)輸入到另一個函數(shù)。 舉個栗子:

# 一個裝飾器
def document_it(func):
    def new_function(*args, **kwargs):
        print("Runing function: ", func.__name__)
        print("Positional arguments: ", args)
        print("Keyword arguments: ", kwargs)
        result = func(*args, **kwargs)
        print("Result: " ,result)
        return result
    return new_function

# 人工賦值
def add_ints(a, b):
    return a + b

cooler_add_ints = document_it(add_ints) #人工對裝飾器賦值
cooler_add_ints(3,5)

# 函數(shù)器前加裝飾器名字
@document_it
def add_ints(a, b):
    return a + b

可以使用多個裝飾器屋吨,多個裝飾由內(nèi)向外向外順序執(zhí)行。

命名空間和作用域
a = 1234
def test():
    print("a = ",a) # True
####
a = 1234
def test():
    a = a -1    #False
    print("a = ",a)

可以使用全局變量 global a 山宾。

a = 1234
def test():
    global a
    a = a -1    #True
    print("a = ",a)

Python 提供了兩個獲取命名空間內(nèi)容的函數(shù) local() global()

___

Python 保留用法至扰。 舉個栗子:

def amazing():
    '''This is the amazing.
    Hello
    world'''
    print("The function named: ", amazing.__name__)
    print("The function docstring is: \n", amazing.__doc__)
異常處理,try...except

只有錯誤發(fā)生時才執(zhí)行的代碼资锰。 舉個栗子:

>>> l = [1,2,3]
>>> index = 5
>>> l[index]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

再試下:

>>> l = [1,2,3]
>>> index = 5
>>> try:
...     l[index]
... except:
...     print("Error: need a position between 0 and", len(l)-1, ", But got", index)
...
Error: need a position between 0 and 2 , But got 5

沒有自定異常類型使用任何錯誤敢课。

獲取異常對象,except exceptiontype as name
short_list = [1,2,3]
while 1:
    value = input("Position [q to quit]? ")
    if value == 'q':
        break
    try:
        position = int(value)
        print(short_list[position])
    except IndexError as err:
        print("Bad index: ", position)
    except Exception as other:
        print("Something else broke: ", other)
自定義異常

異常是一個類绷杜。類 Exception 的子類直秆。

class UppercaseException(Exception):
    pass

words = ['a','b','c','AA']
for i in words:
    if i.isupper():
        raise UppercaseException(i)
# error
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
__main__.UppercaseException: AA

命令行參數(shù)

命令行參數(shù)

python文件:

import sys
print(sys.argv)
PPrint()友好輸出

與print()用法相同,輸出結(jié)果像是列表字典時會不同鞭盟。

子類super()調(diào)用父類方法

舉個栗子:

class Person():
    def __init__(self, name):
        self.name = name

class email(Person):
    def __init__(self, name, email):
        super().__init__(name)
        self.email = email

a = email('me', 'me@me.me')
>>> a.name
... 'me'
>>> a.email
... 'me@me.me’

self.__name 保護私有特性

class Person():
    def __init__(self, name):
        self.__name = name
a = Person('me')
>>> a.name
... AttributeError: 'Person' object has no attribute '__name'

# 小技巧
a._Person__name
實例方法( instance method )

實例方法圾结,以self作為第一個參數(shù),當(dāng)它被調(diào)用時齿诉,Python會把調(diào)用該方法的的對象作為self參數(shù)傳入筝野。

class A():
    count = 2
    def __init__(self): # 這就是一個實例方法
        A.count += 1

類方法 @classmethod

class A():
    count = 2
    def __init__(self):
        A.count += 1
    @classmethod
    def hello(h):
        print("hello",h.count)

注意,使用h.count(類特征)粤剧,而不是self.count(對象特征)歇竟。

靜態(tài)方法 @staticmethod
class A():
    @staticmethod
    def hello():
        print("hello, staticmethod")
>>> A.hello()

創(chuàng)建即用,優(yōu)雅不失風(fēng)格抵恋。

特殊方法(sqecial method)

一個普通方法:

class word():
    def __init__(self, text):
        self.text = text
    def equals(self, word2): #注意
        return self.text.lower() == word2.text.lower()
a1 = word('aa')
a2 = word('AA')
a3 = word('33')
a1.equals(a2)
# True

使用特殊方法:

class word():
    def __init__(self, text):
        self.text = text
    def __eq__(self, word2): #注意焕议,使用__eq__
        return self.text.lower() == word2.text.lower()
a1 = word('aa')
a2 = word('AA')
a3 = word('33')
a1 == a2
# True

其他還有:

*方法名*                        *使用*
__eq__(self, other)            self == other
__ne__(self, other)            self != other
__lt__(self, other)            self < other
__gt__(self, other)            self > other
__le__(self, other)            self <= other
__ge__(self, other)            self >= other

__add__(self, other)        self + other
__sub__(self, other)        self - other
__mul__(self, other)        self * other
__floordiv__(self, other)    self // other
__truediv__(self, other)        self / other
__mod__(self, other)        self % other
__pow__(self, other)        self ** other

__str__(self)                str(self)
__repr__(self)                repr(self)
__len__(self)                len(self)
文本字符串
'%-10d | %-10f | %10s | %10x' % ( 1, 1.2, 'ccc', 0xf )
#
'1          | 1.200000   |        ccc |         33’

{} 和 .format

'{} {} {}'.format(11,22,33)
# 11 22 33
'{2:2d} {0:-10d} {1:10d}'.format(11,22,33)
# :后面是格式標(biāo)識符
# 33 11 22

'{a} {c}'.format(a=11,b=22,c=33)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末弧关,一起剝皮案震驚了整個濱河市盅安,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌世囊,老刑警劉巖宽堆,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異茸习,居然都是意外死亡畜隶,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來籽慢,“玉大人浸遗,你說我怎么就攤上這事∠湟冢” “怎么了跛锌?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長届惋。 經(jīng)常有香客問我髓帽,道長,這世上最難降的妖魔是什么脑豹? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任郑藏,我火速辦了婚禮,結(jié)果婚禮上瘩欺,老公的妹妹穿的比我還像新娘必盖。我一直安慰自己,他們只是感情好俱饿,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布歌粥。 她就那樣靜靜地躺著,像睡著了一般拍埠。 火紅的嫁衣襯著肌膚如雪失驶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天枣购,我揣著相機與錄音突勇,去河邊找鬼。 笑死坷虑,一個胖子當(dāng)著我的面吹牛甲馋,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播迄损,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼定躏,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了芹敌?” 一聲冷哼從身側(cè)響起痊远,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎氏捞,沒想到半個月后碧聪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡液茎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年逞姿,在試婚紗的時候發(fā)現(xiàn)自己被綠了辞嗡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡滞造,死狀恐怖续室,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情谒养,我是刑警寧澤挺狰,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站买窟,受9級特大地震影響丰泊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜始绍,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一瞳购、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧疆虚,春花似錦、人聲如沸满葛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽嘀韧。三九已至篇亭,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锄贷,已是汗流浹背译蒂。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留谊却,地道東北人柔昼。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像炎辨,于是被迫代替她去往敵國和親捕透。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容