Day 11 函数

day11思维导图

一 函数对象 function objects

One of the most powerful features of Python is that everything is an object, including functions. Functions in Python are first-class objects.

This broadly means, that functions in Python: have types can be sent as arguments to another function can be used in expression can become part of various data structures like dictionaries

Example:

Use functions to optimize the branching structure

func_dict={
  "1":["提款",withdraw],
  "2":["转账",transfer],
  "3":["查询余额",check_balance],
  "4":["存款",deposit]
  }

while True:
  print("0 退出")
  for k,v in func_dict.items():
      print(k,v[0])

  choice=input("请输入功能:").strip()
  if choice=="0":
      break

  if choice in func_dict:
      func_dict[choice][1]()
  else:
      print("输入错误")

二 函数嵌套 Nested functions

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.

Example:

use nested functions to find the maximum among the four numbers

def max2(x, y):
  if x > y:
      return x
  else:
      return y


def max4(a, b, c, d):
  res1 = max2(a, b)
  res2 = max2(res1, c)
  res3 = max2(res2, d)
  return res3


print(max4(2, 9, 88, 4))

 

三 名称空间 Namespace

Namespaces in Python. A namespace is a collection of currently defined symbolic names along with information about the object that each name references. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves.

The LEGB rule 名称空间的访问优先级

The LEGB rule is a kind of name lookup procedure, which determines the order in which Python looks up names. For example, if you reference a given name, then Python will look that name up sequentially in the local, enclosing, global, and built-in scope. If the name exists, then you'll get the first occurrence of it.

Examples:

len=10

def func():
  len=20
  print(len)

func()
print(len)
def f1():
  x=555
  def f2():
      x=666
      print(x)
  f2()
x=444
f1()

四 作用域 Scope

Global scope: The names that you define in this scope are available to all your code.

Local scope: The names that you define in this scope are only available or visible to the code within the scope.

The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

The nonlocal keyword

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function.

Use the keyword nonlocal to declare that the variable is not local.

Example:

x = 111


def func():
  global x
  x = 222


func()
print(x)

五 闭包函数 Python Closure

A closure is a nested function which has access to a free variable from an enclosing function that has finished its execution. Three characteristics of a Python closure are:

it is a nested function it has access to a free variable in outer scope it is returned from the enclosing function

A free variable is a variable that is not bound in the local scope. In order for closures to work with immutable variables such as numbers and strings, we have to use the nonlocal keyword.

Python closures help avoiding the usage of global values and provide some form of data hiding. They are used in Python decorators.

def make_printer(msg):

  msg = "hi there"

  def printer():
      print(msg)

  return printer


myprinter = make_printer("Hello there")
myprinter()

 

六 装饰器 Decorator

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.

七 补充:Zen of Python

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

 

原文地址:https://www.cnblogs.com/fengshili666/p/14208687.html