谭子python学习笔记--函数定义及作用域

xiaoxiao2021-02-28  103

函数 函数相关的语句和表达式基础语法 1定义及基本结构2嵌套 作用域法则 1内置作用域2global3模块中的全局变量4嵌套函数的作用域5工厂函数

函数

函数是为了代码最大程度的重用和最小化代码冗余而提供的最基本的程序结构 - 最大化的代码重用和最小化的代码冗余 - 流程分解

函数相关的语句和表达式

语句例子备注Callsfunc(‘spam’,’eggs’)调用函数defdef func(a,b=1,*c)定义returnreturn a+b+c[0]返回值globaldef changer():global xx = ‘new’全局变量yielddef square(x):for i in range(x): yield i**2迭代器lambdafunc=lambda x:x**2匿名函数

说明: - def是可执行代码。函数并不存在,直到Python运行了def后才存在。既是语句其可以与if判断语句、while循环语句、def语句等嵌套使用。在典型的操作中,def语句在模块文件中编写,并自然而然的在模块文件中第一次导入的时候生成定义。 - def创建了一个对象并将其赋值给某个变量名当Python运行到def时,它将会生成一个新的函数对象并将其赋值给这个函数名。 - lambda创建一个对象但将其作为结果返回 - return将一个结果对象发送给调用者 - yield向调用者发回一个结果对象,但是记住它离开的地方 - global声明了一个模块级的便令并被赋值。变量名往往需要关注它的作用域(也就是说变量存储的地方) - 函数是通过赋值(对象引用传递的) - 参数、返回值 变量并不是声明

基础语法

1)定义及基本结构

def <name>(arg1,arg2,... argN): <statement> [return <value>] [yield <value>]

2)嵌套

def my_func(s,flag=1): print flag if flag == 1: def func(s): return s + ' world!' elif flag == 2: def func(s): return s%10 else: return -1 return func(s) print my_func('hello')

作用域法则

内嵌的模块是全局作用域全局作用域的作用范围仅限于单个文件每次函数的调用都创建了一个新的本地作用域赋值的变量除非声明为全局变量,否则均为本地变量所有其他的变量名都可以归纳为本地、全局或内置的

example:

x = 99 def func(y): z = x + y return z func(1)

说明: 全局变量名:x,func 本地变量名:y,z y和z都是本地变量,因为他们都是在函数定义内部进行赋值的,变量的赋值将改变函数的作用域

1)内置作用域

>>> import __builtin__ >>> dir(__builtin__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

2)global

尽量少使用全局变量

x = 99 def func(z,y): global x x = x + y return x func(1,2)

3)模块中的全局变量

模块:test.py

x = 99 def func(z,y): global x x = x + y return x

加载模块,访问变量

import test print test.x print test.func(1,2)

4)嵌套函数的作用域

x = 99 y = 80 def f1(): x = 88 def f2(): print x print y f2() f1()

5)工厂函数

def maker(N): def action(X): return X**N return action f = maker(2) f(3)
转载请注明原文地址: https://www.6miu.com/read-62885.html

最新回复(0)