找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 2248|回复: 0

[代码与实例] 你知道python解释器什么时候计算各个代码块吗?

0

主题

3

帖子

3

积分

贫民

积分
3
Z-zag 发表于 2019-4-18 16:14:52 | 显示全部楼层 |阅读模式
本帖最后由 Z-zag 于 2019-4-18 17:16 编辑
  1. # evaltime.py
  2. from evalsupport import deco_alpha

  3. print('<[1]> evaltime 模块开始')


  4. class ClassOne:
  5.     print('<[2]> classOne 定义体')

  6.     def __init__(self):
  7.         print('<[3]> classOne 的 __init__方法 ')

  8.     def __del__(self):
  9.         print('<[4]> classOne 的 __del__方法')

  10.     def method_x(self):
  11.         print('<[5]> classOne 的 method_x 方法')

  12.     class ClassTwo:
  13.         print('<[6]>ClassTwo 嵌套的类')


  14. @deco_alpha
  15. class ClassThree:
  16.     print('<[7]> ClassThree 定义体')

  17.     def method_y(self):
  18.         print('<[8]> ClassThree 被装饰的方法 method_y')


  19. class ClassFour(ClassThree):
  20.     print('<[9]> ClassFour 定义体')

  21.     def method_y(self):
  22.         print('<[10]>ClassFour 的 method_y 方法')


  23. if __name__ == '__main__':
  24.     print('<[11]> ClassOne test', 30 * '.')
  25.     one = ClassOne()
  26.     one.method_x()
  27.     print('<[12]> ClassThree test', 30 * '.')
  28.     three = ClassThree()
  29.     three.method_y()
  30.     print('<[13]> ClassFour test', 30 * '.')
  31.     four = ClassFour()
  32.     four.method_y()

  33. print('<[14]> evaltime 模块结束')

复制代码
  1. # evalsupport.py
  2. print('<[100]> evalsupport 模块开始')


  3. def deco_alpha(cls):
  4.     print('<[200]> deco alpha函数定义体')

  5.     def inner_1(self):
  6.         print('<[300]> deco_alpha函数中的inner_1函数')

  7.     cls.method_y = inner_1
  8.     return cls


  9. class MetaAleph(type):
  10.     print('<[400]> MetaAleph 类 的定义体')

  11.     def __init__(cls, name, bases, dic):
  12.         print('<[500]> MetaAlpha 的 __init__方法')

  13.         def inner_2(self):
  14.             print('<[600]> MetaAleph 的 init 中的方法inner_2')

  15.         cls.method_z = inner_2


  16. print('<[700]> evalsupport模块结束的打印')
复制代码

分享一个小测试,测试一下 你对python解释器的执行有多少了解。
先不要运行代码, 自己算一算 输出应该是什么?

python解释器在 ‘导入时’ 和 ‘运行时’对代码的编译有何不同呢?
    通过这个小测试,你将更加清楚的知道。
    在终端中执行   python3 evaltime.py
    在python shell中执行  >>>import evaltime

代码源自《流畅的python》 强烈推荐!!!



evalsupport.py

589 Bytes, 下载次数: 0

evaltime.py

1.04 KB, 下载次数: 0

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表