空间 体重 main show pow eth 内存 cit
正确理解 Python 函数,能够帮助我们更好地理解 Python 装饰器、匿名函数(lambda)、函数式编程等高阶技术。
函数(Function)作为程序语言中不可或缺的一部分,太稀松平常了。但函数作为第一类对象(First-Class Object)却是 Python 函数的一大特性。那到底什么是第一类对象(First-Class Object)呢?
在 Python 中万物皆为对象,函数作为第一类对象有如下特性:
- #函数身为一个对象,拥有对象模型的三个通用属性:id(内存地址)、类型、和值
- def foo(text):
- return len(text)
- print(type(foo)) #函数类型
- print(id(foo))#函数id 内存地址
- print(foo)#函数值
- #函数可以被引用,即函数可以赋值给一个变量
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- def foo():
- print('from foo')
- foo()
- func=foo #引用,赋值
- print(foo)
- print(func)
- func()输出:from foo内存地址一样说明func引用的是foo函数地址,也就是foo将地址赋值给func变量
- #容器对象(list、dict、set等)中可以存放任何对象,包括整数、字符串,函数也可以作存放到容器对象中
- def foo():
- print("hanjialong")
- dif={"func":foo}
- # foo()
- if __name__ == '__main__':
- dif={"func":foo}
- dif["func"]()
- #比较函数地址
- def foo():
- print("hanjialong")
- dif={"func":foo}
- print(foo)
- # dif={"func":foo}
- # dif["func"]()
- print(dif["func"])
- def foo(name):#传入数据类型并计算长度
- size = len(name)
- return size #将结果return
- def show(func):
- size = func("jjjjj")#相当于在show函数内部运行foo函数,size接受foo函数的return结果
- print("length of string is %s"%size)show(foo)
- """
- 函数接受一个或多个函数作为输入或者函数输出(返回)的值是函数时,我们称这样的函数为高阶函数
- """
- def foo():
- print("返回值")
- def bar(func):
- return func
- f = bar(foo)
- f()
- bar(foo())
- 1、嵌套调用
- #嵌套函数的意义相当于把一个大需求拆成多个小需求然后组合一起,以如下为例
- max2函数式做两个值得大小比如如果要做多个如10 100个就需要在max4中组合
- def max2(x,y):
- return x if x > y else y
- def max4(a,b,c,d):
- res1=max2(a,b)
- res2=max2(res1,c)
- res3=max2(res2,d)
- return res3
- print(max4(10,99,31,22))
- 2、函数嵌套定义
- #函数的嵌套定义def f1():#第一步进入f1函数def f2():#第二部f1函数体中有f2函数声明print('from f2')def f3():#第四部f2函数体中有f3函数声明print('from f3')f3()#第五部f2函数体中运行f3函数f2()#第三部f1函数体重运行f2内容f1()
1. 命名空间定义
命名空间是名字和对象的映射,就像是字典,key 是变量名,value 是变量的值
- #定义名字的方法
- import time
- name='egon' #定义变量
- def func(): #定义函数
- pass
- class Foo:#定义类
- pass
2. 命名空间的分类
- print(sum)
- print(max)
- print(min)
- print(max([1,2,3]))
- import builtins
- for i in dir(builtins): #打印所有的内置函数
- print(i)
- 复制代码
- 结果:
- C:\Python\Python36\python.exe D:/Python/课件/day4/cc.py
- <built-in function sum>
- <built-in function max>
- <built-in function min>
- 3
- ArithmeticError
- AssertionError
- AttributeError
- BaseException
- BlockingIOError
- BrokenPipeError
- BufferError
- BytesWarning
- ChildProcessError
- ConnectionAbortedError
- ConnectionError
- ConnectionRefusedError
- ConnectionResetError
- DeprecationWarning
- EOFError
- Ellipsis
- EnvironmentError
- Exception
- False
- FileExistsError
- FileNotFoundError
- FloatingPointError
- FutureWarning
- GeneratorExit
- IOError
- ImportError
- ImportWarning
- IndentationError
- IndexError
- InterruptedError
- IsADirectoryError
- KeyError
- KeyboardInterrupt
- LookupError
- MemoryError
- ModuleNotFoundError
- NameError
- None
- NotADirectoryError
- NotImplemented
- NotImplementedError
- OSError
- OverflowError
- PendingDeprecationWarning
- PermissionError
- ProcessLookupError
- RecursionError
- ReferenceError
- ResourceWarning
- RuntimeError
- RuntimeWarning
- StopAsyncIteration
- StopIteration
- SyntaxError
- SyntaxWarning
- SystemError
- SystemExit
- TabError
- TimeoutError
- True
- TypeError
- UnboundLocalError
- UnicodeDecodeError
- UnicodeEncodeError
- UnicodeError
- UnicodeTranslateError
- UnicodeWarning
- UserWarning
- ValueError
- Warning
- WindowsError
- ZeroDivisionError
- __build_class__
- __debug__
- __doc__
- __import__
- __loader__
- __name__
- __package__
- __spec__
- abs
- all
- any
- ascii
- bin
- bool
- bytearray
- bytes
- callable
- chr
- classmethod
- compile
- complex
- copyright
- credits
- delattr
- dict
- dir
- divmod
- enumerate
- eval
- exec
- exit
- filter
- float
- format
- frozenset
- getattr
- globals
- hasattr
- hash
- help
- hex
- id
- input
- int
- isinstance
- issubclass
- iter
- len
- license
- list
- locals
- map
- max
- memoryview
- min
- next
- object
- oct
- open
- ord
- pow
- property
- quit
- range
- repr
- reversed
- round
- set
- setattr
- slice
- sorted
- staticmethod
- str
- sum
- super
- tuple
- type
- vars
- zip
- Process finished with exit code 0
- x=1 #全局命名空间
- def func():
- money=2000 #非全局
- x=2
- print('func',x)#打印的是x=2的值如果没有将打印全局的
- print(x)#打印的是全局
- print(func)
- func()
- x=10000#全局
- def func():
- x=1#局部
- def f1():
- pass
3. 作用域
- 名字的查找顺序:局部名称空间---》全局名层空间---》内置名称空间
Python 函数对象、生成器 、装饰器、迭代器、闭包函数
来源: http://www.bubuko.com/infodetail-2084549.html