一、命名空间与作用域

命名空间是名字和对象的映射,就像是字典,key是变量名,value是变量的值

1.命名空间的定义

  1. name='egon' #定义变量
  2.  
  3. def func(): #定义函数
  4. pass
  5.  
  6. class Foo:  #定义类
  7. pass

2.命名空间的分类

  • 1.内置名称空间: 随着python解释器的启动而产生,包括异常类型、内建函数和特殊方法,可以代码中任意地方调用
  1. print(sum)
  2. print(max)
  3. print(min)
  4.  
  5. print(max([1,2,3]))
  6.  
  7. import builtins
  8. for i in dir(builtins): #打印所有的内置函数
  9. print(i)

输出

  1. <built-in function sum>
  2. <built-in function max>
  3. <built-in function min>
  4. 3
  5. ArithmeticError
  6. AssertionError
  7. AttributeError
  8. BaseException
  9. BlockingIOError
  10. BrokenPipeError
  11. BufferError
  12. BytesWarning
  13. ChildProcessError
  14. ConnectionAbortedError
  15. ConnectionError
  16. ConnectionRefusedError
  17. ConnectionResetError
  18. DeprecationWarning
  19. EOFError
  20. Ellipsis
  21. EnvironmentError
  22. Exception
  23. False
  24. FileExistsError
  25. FileNotFoundError
  26. FloatingPointError
  27. FutureWarning
  28. GeneratorExit
  29. IOError
  30. ImportError
  31. ImportWarning
  32. IndentationError
  33. IndexError
  34. InterruptedError
  35. IsADirectoryError
  36. KeyError
  37. KeyboardInterrupt
  38. LookupError
  39. MemoryError
  40. NameError
  41. None
  42. NotADirectoryError
  43. NotImplemented
  44. NotImplementedError
  45. OSError
  46. OverflowError
  47. PendingDeprecationWarning
  48. PermissionError
  49. ProcessLookupError
  50. RecursionError
  51. ReferenceError
  52. ResourceWarning
  53. RuntimeError
  54. RuntimeWarning
  55. StopAsyncIteration
  56. StopIteration
  57. SyntaxError
  58. SyntaxWarning
  59. SystemError
  60. SystemExit
  61. TabError
  62. TimeoutError
  63. True
  64. TypeError
  65. UnboundLocalError
  66. UnicodeDecodeError
  67. UnicodeEncodeError
  68. UnicodeError
  69. UnicodeTranslateError
  70. UnicodeWarning
  71. UserWarning
  72. ValueError
  73. Warning
  74. ZeroDivisionError
  75. __build_class__
  76. __debug__
  77. __doc__
  78. __import__
  79. __loader__
  80. __name__
  81. __package__
  82. __spec__
  83. abs
  84. all
  85. any
  86. ascii
  87. bin
  88. bool
  89. bytearray
  90. bytes
  91. callable
  92. chr
  93. classmethod
  94. compile
  95. complex
  96. copyright
  97. credits
  98. delattr
  99. dict
  100. dir
  101. divmod
  102. enumerate
  103. eval
  104. exec
  105. exit
  106. filter
  107. float
  108. format
  109. frozenset
  110. getattr
  111. globals
  112. hasattr
  113. hash
  114. help
  115. hex
  116. id
  117. input
  118. int
  119. isinstance
  120. issubclass
  121. iter
  122. len
  123. license
  124. list
  125. locals
  126. map
  127. max
  128. memoryview
  129. min
  130. next
  131. object
  132. oct
  133. open
  134. ord
  135. pow
  136. print
  137. property
  138. quit
  139. range
  140. repr
  141. reversed
  142. round
  143. set
  144. setattr
  145. slice
  146. sorted
  147. staticmethod
  148. str
  149. sum
  150. super
  151. tuple
  152. type
  153. vars
  154. zip
  • 2.全局名称空间:文件的执行会产生全局名称空间,指的是文件级别定义的名字都会放入该空间
  1. x=1 #全局命名空间
  2.  
  3. def func():
  4. money=2000 #非全局
  5. x=2
  6. print('func')
  7. print(x)
  8. print(func)
  9. func()
  • 3.局部名称空间:调用函数时会产生局部名称空间,只在函数调用时临时绑定,调用结束解绑定
  1. x=10000    #全局
  2. def func():
  3. x=1    #局部
  4. def f1():
  5. pass

3.作用域

命名空间的可见性就是作用域

  • 1. 全局作用域:内置名称空间,全局名称空间
  • 2. 局部作用域:局部名称空间

名字的查找顺序:局部名称空间---》全局名层空间---》内置名称空间

查看全局作用域内的名字:gloabls()

查看局部作用域内的名字:locals()

全局作用域的名字:全局有效,在任何位置都能被访问到,除非del删掉,否则会一直存活到文件执行完毕

局部作用域的名字:局部有效,只能在局部范围调用,只在函数调用时才有效,调用结束就失效

  1. x=1000
  2. def func(y):
  3. x=2
  4. print(locals())
  5. print(globals())
  6.  
  7. func(1)

输出

  1. {'y': 1, 'x': 2}
  2. {'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10c436c88>, '__package__': None, '__cached__': None, '__file__': '/Users/hexin/PycharmProjects/py3/day4/2.py', 'func': <function func at 0x10c3c9f28>, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, '__doc__': None, 'time': <module 'time' (built-in)>, '__name__': '__main__', 'x': 1000}

二、闭包函数

简单来说,一个闭包就是你调用了一个函数A,这个函数A返回了一个函数B给你。这个返回的函数B就叫做闭包。

闭包函数须满足以下条件:

1. 定义在内部函数;
2. 包含对外部作用域而非全局作用域的引用;

  1. def f1():
  2. x = 1
  3. def f2():
  4. print(x)
  5. return f2
  6.  
  7. f=f1()
  8. print(f)
  9.  
  10. x=100
  11. f()
  12. print(x)

输出

  1. <function f1.<locals>.f2 at 0x107714400>
  2. 1
  3. 100

闭包应用

  1. from urllib.request import urlopen
  2.  
  3. def index(url):
  4. def get():
  5. return urlopen(url).read()
  6. return get
  7.  
  8. oldboy=index('http://crm.oldboyedu.com')
  9.  
  10. print(oldboy().decode('utf-8'))

输出

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>OldboyCRM</title>
  6. <!--Bootstrap Stylesheet [ REQUIRED ]-->
  7. <link href="/static/css/bootstrap.min.css" rel="stylesheet">
  8. <link href="/static/css/custom.css" rel="stylesheet">
  9.  
  10. <!--Nifty Stylesheet [ REQUIRED ]-->
  11. <link href="/static/css/nifty.min.css" rel="stylesheet">
  12.  
  13. <!--Font Awesome [ OPTIONAL ]-->
  14. <link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet">
  15.  
  16. <!--Bootstrap Validator [ OPTIONAL ]-->
  17. <link href="/static/plugins/bootstrap-validator/bootstrapValidator.min.css" rel="stylesheet">
  18.  
  19. <!--Demo [ DEMONSTRATION ]-->
  20. <link href="/static/css/demo/nifty-demo.min.css" rel="stylesheet">
  21.  
  22. <!--Bootstrap Datepicker [ OPTIONAL ]-->
  23. <link href="/static/plugins/bootstrap-datepicker/bootstrap-datepicker.css" rel="stylesheet">
  24.  
  25. </head>
  26. <body>
  27.  
  28. <div id="container" class="effect mainnav-lg">
  29. <div id="page-title">
  30. <h1 class="page-header text-overflow">老男孩IT教育 | 只培养技术精英</h1>
  31.  
  32. </div>
  33.  
  34. <div id="page-content">
  35.  
  36. <div class="row">
  37.  
  38. <div class="col-lg-12">
  39.  
  40. <div class="panel">
  41. <div class="panel-heading">
  42. <h3 class="panel-title">学员平台</h3>
  43. </div>
  44. <div class="panel-body" style="">
  45.  
  46. <h4><a class="btn-link" href="/grade/single/">成绩查询</a></h4>
  47. <h4><a class="btn-link" href="/scholarship/">奖学金政策</a></h4>
  48. <h4><a class="btn-link" href="/training_contract/">培训协议查询</a></h4>
  49. <h4><a class="btn-link" href="/compliant/">投诉建议</a></h4>
  50. <h4><a class="btn-link" href="/stu_faq/">学员常见问题汇总</a></h4>
  51. <h4><a class="btn-link" href="/stu/">学员登录</a></h4>
  52.  
  53. </div> <!--end panel-body-->
  54. </div> <!--end panel-->
  55. </div> <!--end col-lg-12-->
  56. </div><!--end row-->
  57.  
  58. </div><!--end page-content-->
  59.  
  60. </div>
  61.  
  62. <!--jQuery [ REQUIRED ]-->
  63. <script src="/static/js/jquery-2.1.1.min.js"></script>
  64.  
  65. <!--BootstrapJS [ RECOMMENDED ]-->
  66. <script src="/static/js/bootstrap.min.js"></script>
  67.  
  68. <!--Nifty Admin [ RECOMMENDED ]-->
  69. <script src="/static/js/nifty.min.js"></script>
  70.  
  71. <!--jquery-cookie-->
  72. <script src="/static/js/jquery.cookie.js"></script>
  73.  
  74. <script src="/static/js/ajax_comm.js"></script>
  75.  
  76. <!--Bootstrap Wizard [ OPTIONAL ]-->
  77. <script src="/static/plugins/bootstrap-wizard/jquery.bootstrap.wizard.min.js"></script>
  78.  
  79. <!--Bootstrap Validator [ OPTIONAL ]-->
  80. <script src="/static/plugins/bootstrap-validator/bootstrapValidator.min.js"></script>
  81.  
  82. <!--Demo script [ DEMONSTRATION ]-->
  83. <script src="/static/js/demo/nifty-demo.min.js"></script>
  84.  
  85. <!--Form Wizard [ SAMPLE ]-->
  86. <script src="/static/js/demo/form-wizard.js"></script>
  87.  
  88. <!--Bootstrap Datepicker [ OPTIONAL ]-->
  89. <script src="/static/plugins/bootstrap-datepicker/bootstrap-datepicker.js"></script>
  90.  
  91. </body>
  92. </html>

三、装饰器

1.定义

装饰器:修饰别人的工具,修饰添加功能,工具指的是函数

装饰器本身可以是任何可调用对象,被装饰的对象也可以是任意可调用对象

2.为什么要用装饰器?

开放封闭原则:对修改是封闭的,对扩展是开放的
装饰器就是为了在不修改被装饰对象的源代码以及调用方式的前提下,为其添加新功能

3.装饰器的实现

装饰器的功能是将被装饰的函数当作参数传递给与装饰器对应的函数(名称相同的函数),并返回包装后的被装饰的函数”

直接看示意图,其中 a 为与装饰器 @a 对应的函数, b 为装饰器修饰的函数,装饰器@a的作用是:

简而言之:@a 就是将 b 传递给 a(),并返回新的 b = a(b)

例如

  1. def a(name):      #与装饰器对应的函数
  2. return name()
  3.  
  4. @a            #装饰器 b = a(b)
  5. def b():        #被装饰函数
  6. print('hexin')

输出

hexin

解析过程是这样子的:
1.python 解释器发现@a,就去调用与其对应的函数( a 函数)
2.a 函数调用前要指定一个参数,传入的就是@a下面修饰的函数,也就是 b()
3.a() 函数执行,调用 b(),b() 打印“hexin”

5.装饰器的应用

  1. import time
  2.  
  3. def timmer(func):
  4. def wrapper():
  5. start_time=time.time()
  6. func()       #index()
  7. stop_time=time.time()
  8. print('run time is %s' %(stop_time-start_time))
  9. return wrapper
  10.  
  11. @timmer       #index=timmer(index)
  12. def index():
  13. time.sleep(1)
  14. print('welcome to index')
  15.  
  16. index()

输出

  1. welcome to index
  2. run time is 1.005241870880127

例子

  1. login_user={'user':None,'status':False}
  2. def auth(func):
  3. def wrapper(*args,**kwargs):
  4. if login_user['user'] and login_user['status']:
  5. res=func(*args,**kwargs)
  6. return res
  7. else:
  8. name=input('请输入用户名: ')
  9. password=input('请输入密码: ')
  10. if name == 'hexin' and password == '':
  11. login_user['user']='hexin'
  12. login_user['status']=True
  13. print('\033[45mlogin successful\033[0m')
  14. res=func(*args,**kwargs)
  15. return res
  16. else:
  17. print('\033[45mlogin err\033[0m')
  18. return wrapper
  19.  
  20. @auth #index=auth(index)
  21. def index():
  22. print('welcome to index page')
  23.  
  24. @auth #home=auth(home)
  25. def home(name):
  26. print('%s welcome to home page' %name)
  27.  
  28. index()
  29. home('hexin')

输出

  1. 请输入用户名: heixn
  2. 请输入密码: 123
  3. login err
  4. 请输入用户名: hexin
  5. 请输入密码: 123
  6. login successful
  7. hexin welcome to home page

补充:

装饰器的基本框架:

  1. def timer(func):
  2. def wrapper():
  3. func()
  4. return wrapper

带参数

  1. def timer(func):
  2. def wrapper(*args,**kwargs):
  3. func(*args,**kwargs)
  4. return wrapper

【Python 函数对象 命名空间与作用域 闭包函数 装饰器 迭代器 内置函数】的更多相关文章

  1. Python--函数对象@命名空间与作用域@包函数@装饰器@迭代器@内置函数

    一.函数对象 函数(Function)作为程序语言中不可或缺的一部分,但函数作为第一类对象(First-Class Object)却是 Python 函数的一大特性. 那到底什么是第一类对象(Firs ...

  2. 万恶之源 - Python装饰器及内置函数

    装饰器 听名字应该知道这是一个装饰的东西,我们今天就来讲解一下装饰器,有的铁子们应该听说,有的没有听说过.没有关系我告诉你们这是一个很神奇的东西 这个有多神奇呢? 我们先来复习一下闭包 def fun ...

  3. Python装饰器及内置函数

    装饰器 听名字应该知道这是一个装饰的东西,我们今天就来讲解一下装饰器,有的铁子们应该听说,有的没有听说过.没有关系我告诉你们这是一个很神奇的东西 这个有多神奇呢? 我们先来复习一下闭包 def fun ...

  4. Python装饰器、内置函数之金兰契友

    装饰器:装饰器的实质就是一个闭包,而闭包又是嵌套函数的一种.所以也可以理解装饰器是一种特殊的函数.因为程序一般都遵守开放封闭原则,软件在设计初期不可能把所有情况都想到,所以一般软件都支持功能上的扩展, ...

  5. python笔记5:装饰器、内置函数、json

    装饰器 装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象. 先看简单例子: def run(): time.sleep(1 ...

  6. python 之 面向对象(多态性、装饰器方法 内置函数补充)

    7.6 多态性 1 什么是多态性 多态指的是同一种事物多种形态,在程序中用继承可以表现出多态.多态性:可以在不用考虑对象具体类型的前提下而直接使用对象下的方法 2.为什要用多态 用基类创建一套统一的规 ...

  7. 文成小盆友python-num4 装饰器,内置函数

    一 .python 内置函数补充 chr()  -- 返回所给参数对应的 ASCII 对应的字符,与ord()相反 # -*- coding:utf-8 -*- # Author:wencheng.z ...

  8. day0318装饰器和内置函数

    一.装饰器 1.装饰器: 解释:装饰器的本事就是一个函数,不改动主代码的情况下,增加新功能.返回值也是一个函数对象. 2.装饰器工作过程 import time def func(): print(' ...

  9. Fluent_Python_Part3函数即对象,07-closure-decoration,闭包与装饰器

    第7章 函数装饰器和闭包 装饰器用于在源码中"标记"函数,动态地增强函数的行为. 了解装饰器前提是理解闭包. 闭包除了在装饰器中有用以外,还是回调式编程和函数式编程风格的基础. 1 ...

随机推荐

  1. 老李分享:接电话之uiautomator 1

    老李分享:接电话之uiautomator   poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.如果对课程感兴趣,请大家咨询qq:9 ...

  2. 测试开发Python培训:实现屌丝的黄色图片收藏愿望(小插曲)

    男学员在学习python的自动化过程中对于爬虫很感兴趣,有些学员就想能收藏一些情色图片,供自己欣赏.作为讲师只能是满足愿望,帮助大家实现对美的追求,http://wanimal.lofter.com/ ...

  3. 如何高效实现扫描局域网IP、主机名、MAC和端口

    近几年工作经常使用RFID识读器,智能家居网关,温湿度传感器.串口服务器.视频编码器等,一般是有串口和网口,由于现场原因一般较少使用串口,大多使用网口.连接方法是IP地址和端口,有的设备带搜索软件,有 ...

  4. java基础--动态代理实现与原理详细分析

    关于Java中的动态代理,我们首先需要了解的是一种常用的设计模式--代理模式,而对于代理,根据创建代理类的时间点,又可以分为静态代理和动态代理. 一.代理模式                     ...

  5. jmeter JDBC 连接数据库

    1.添加JDBC Connection Configuration 2.添加JDBC Request 3.添加查看结果树 4. 设置下列参数:Database URL:jdbc:mysql://hos ...

  6. Python爬虫 URLError异常处理

    1.URLError 首先解释下URLError可能产生的原因: 网络无连接,即本机无法上网 连接不到特定的服务器 服务器不存在 在代码中,我们需要用try-except语句来包围并捕获相应的异常.下 ...

  7. Python3.5爬虫统计AcFun所有视频,并按各个类别进行Top100排序展示

    前(b)言(b): 前段时间对Python产生了浓厚的兴趣,所以决定入门学习了1个多月,后来某时我需要对tomcat做一个压力测试,于是我想到了用Python写一个压力测试的脚本吧!最后捣鼓出了一个脚 ...

  8. 最新windows 0day漏洞利用

    利用视屏:https://v.qq.com/iframe/player.html?vid=g0393qtgvj0&tiny=0&auto=0 使用方法 环境搭建 注意,必须安装32位p ...

  9. php判断多维数组的技巧

    直接上代码吧: if(count($array) == count($array, 1)){ echo '一维数组'; }else{ echo '多维数组'; } 看了下手册 int count (m ...

  10. 一款好用的jquery评分插件

    一.使用说明 1.jQuery评分插件的功能: 图标显示用户评分,更美观 可实时点击,切换评分 返回用户评分,记录用户评分 实现类似下图效果 2.优点: 美观,方便 3.缺点: 只能用于jquery开 ...