Python 函数 类 语法糖

原文作者:zzir

Python 语法糖

\,换行连接
s = ''
s += 'a' + \
     'b' + \
     'c'
n = 1 + 2 + \
3
# 6
while,for 循环外的 else

如果 while 循环正常结束(没有break退出)就会执行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’)]

列表推导式
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]
字典推导式

{ key_exp : value_exp fro expression in iterable }

#查询每个字母出现的次数。
strs = 'Hello World'
s = { k : strs.count(k) for k in set(strs) }
集合推导式

{expression for expression in iterable }

元组没有推导式

本以为元组推导式是列表推导式改成括号,后来发现那个 生成器推导式。

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

函数

函数关键字参数,默认参数值
def do(a=0,b,c)
    return (a,b,c)

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

函数默认参数值在函数定义时已经计算出来,而不是在程序运行时。
列表字典等可变数据类型不可以作为默认参数值。

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 收集位置参数
def do(*args):
    print(args)
do(1,2,3)
(1,2,3,'d’)
**kwargs 收集关键字参数
def do(**kwargs):
  print(kwargs)
do(a=1,b=2,c='la')
# {'c': 'la', 'a': 1, 'b': 2}
lamba 匿名函数
a = lambda x: x*x
a(4)
# 16
生成器

生成器是用来创建Python序列的一个对象。可以用它迭代序列而不需要在内存中创建和存储整个序列。
通常,生成器是为迭代器产生数据的。

生成器函数函数和普通函数类似,返回值使用 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>
装饰器

有时需要在不改变源代码的情况下修改已经存在的函数。
装饰器实质上是一个函数,它把函数作为参数输入到另一个函数。 举个栗子:

# 一个装饰器
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)

# 函数器前加装饰器名字
@document_it
def add_ints(a, b):
    return a + b

可以使用多个装饰器,多个装饰由内向外向外顺序执行。

命名空间和作用域
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 提供了两个获取命名空间内容的函数 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

只有错误发生时才执行的代码。 举个栗子:

>>> 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

命令行参数

命令行参数

python文件:

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

与print()用法相同,输出结果像是列表字典时会不同。

子类super()调用父类方法

举个栗子:

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作为第一个参数,当它被调用时,Python会把调用该方法的的对象作为self参数传入。

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(对象特征)。

静态方法 @staticmethod
class A():
    @staticmethod
    def hello():
        print("hello, staticmethod")
>>> A.hello()

创建即用,优雅不失风格。

特殊方法(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)
# :后面是格式标识符
# 33 11 22

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,200评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,526评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,321评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,601评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,446评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,345评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,753评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,405评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,712评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,743评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,529评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,369评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,770评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,026评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,301评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,732评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,927评论 2 336

推荐阅读更多精彩内容