这里有5个Python技巧,这些技巧使编写代码比以往任何时候都更有效率。可以编写更好,更紧凑的Python代码。
1.生成器Generator函数
Generator函数是一种特殊类型的函数,它不返回单个值,而是返回带有一系列值的迭代器对象:
def mygenerator(): print('First item') yield 10
print('Second item') yield 20
print('Last item') yield 30
|
>>> gen = mygenerator()
>>> next(gen)
First item
10
>>> next(gen)
Second item
20
>>> next(gen)
Last item
30
它使用yield而不是return关键字。因此,yield每次调用时都会针对关键字返回值。但是,您需要为此函数创建一个迭代器如next();生成器函数不能包含return关键字。如果包含它,它将终止该功能,return语句返回值并终止函数的执行。
2.装饰器decorator
装饰器是Python中的一种设计模式,它允许用户向现有对象添加新功能而无需修改其结构。
def a_new_decorator(a_func):
def wrapTheFunction(): print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def a_function_requiring_decoration(): print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration() outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration) now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration() outputs:I am doing some boring work before executing a_func() # I am the function which needs some decoration to remove my foul smell # I am doing some boring work after executing a_func()
|
装饰器用来包装函数并以一种或另一种方式修改其行为。
3.三元运算符
三元运算符在Python中通常被称为条件表达式。这些运算符根据条件是否成立来评估某些内容。他们成为2.4版Python的一部分
is_nice = True state = "nice" if is_nice else "not nice"
|
它允许快速测试条件而不是使用多行if语句。通常,它可能非常有用,并且可以使您的代码紧凑但仍可维护。
4.Setattr和getattr setattr函数
set指定对象的指定属性的值。getattr方法返回对象的命名属性的值。
5.枚举
枚举为可迭代对象添加计数器,并以枚举对象的形式返回。
Python通过为该任务提供内置函数enumerate()减轻了程序员的任务。 Enumerate()方法向可迭代对象添加一个计数器,并以枚举对象的形式返回它。然后可以将此枚举对象直接用于for循环,或使用list()方法将其转换为元组列表。
python # Python program to illustrate # enumerate function l1 = ["eat","sleep","repeat"] s1 = "geek" # creating enumerate objects obj1 = enumerate(l1) obj2 = enumerate(s1) print ("Return type:",type(obj1)) print (list(enumerate(l1))) # changing start index to 2 from 0 print (list(enumerate(s1,2))) 输出: Return type: < type 'enumerate' > [(0, 'eat'), (1, 'sleep'), (2, 'repeat')] [(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]
|