枚举(enumerate)是Python内置函数。它的用处很难在简单的一行中说明,但是大多数的新人,甚至一些高级程序员都没有意识到它。它允许我们遍历数据并自动计数,下面是一个例子:for counter, value in enumerate(some_list): print(counter, value)不只如此,enumerate也接受一些可选参数,这使它更有用。
那如果你想从一个函数里返回两个变量而不是一个呢?新手们有若干种方法。最著名的方法,是使用global关键字。让我们看下这个没用的例子:def profile(): global name global age name = "Danny" age = 30profile()print(name)# Output: Dannyprint(age)# Output: 30注意: 不要试着使用上述方法。重要的事情说三遍,不要试着使用上述方法!
装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于Flask和Django web框架中。这里是一个例子来使用基于装饰器的授权:from functools import wrapsdef requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.
def hi(): return "hi yasoob!"def doSomethingBeforeHi(func): print("I am doing some boring work before executing hi()") print(func())doSomethingBeforeHi(hi)#outputs:I am doing some boring work before executing hi()# hi yasoob!现在你已经具备所有必需知识,来进一步学习装饰器真正是什么了。装饰器让你在一个函数的前后去执行代码。
其实并不需要在一个函数里去执行另一个函数,我们也可以将其作为输出返回出来:def hi(name="yasoob"): def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" if name == "yasoob": return greet else: return welcomea = hi()print(a)#output…