• python中的嵌套类


    python中的嵌套类

    在.NET和JAVA语言中看到过嵌套类的实现,作为外部类一个局部工具还是很有用的,今天在python也看到了很不错支持一下。动态语言中很好的嵌套类的实现,应该说嵌套类解决设计问题同时简化了程序,值得学习。

     1 import threading, sys
     2  
     3 def nested1(timeout):
     4     def _1(function):
     5         def _2(*args,**kw):
     6             class child(threading.Thread):
     7                 def __init__(self):
     8                     threading.Thread.__init__(self)
     9                     self.result=None
    10                     self.error = None
    11                     
    12                     self.setDaemon(True)
    13                     self.start()
    14  
    15                 def run(self):
    16                     try:
    17                         self.result = function(*args, **kw)
    18                     except:
    19                         self.error = sys.exc_info()
    20  
    21             c = child()
    22             c.join(timeout)
    23             if c.isAlive():
    24                 raise TimeoutError, 'took too long'
    25             if c.error:
    26                 raise c.error[0], c.error[1]
    27             return c.result
    28         return _2
    29     return _1
    30 def test(a, b):
    31     for i in xrange(100000):
    32         a = a+b
    33     return a
    34  
    35  
    36 if __name__ == '__main__':
    37     nested1 = nested1(2)
    38     nested2 = nested1(test)
    39     print nested2(2,3)
    40  
    41     a =  nested2.child()
    42     print a

    上面是一个借鉴web.py框架中的一个例子,下面print a部分是我的测试,发现函数对象不能引用内层的类,这里的实现可以发现比独立写多个函数和类减少很多代码

    再看个例子:

     1 import os, sys
     2  
     3 class parent:
     4     def __init__(self):
     5         self.name = 'parent'
     6  
     7     def getName(self):
     8         print self.name
     9  
    10     class child:
    11         def __init__(self):
    12             self.name = 'child'
    13  
    14         def getName(self):
    15             print self.name
    16  
    17  
    18 if __name__ == '__main__':
    19     child =  parent.child()
    20     child.getName()

    这里从父类引用内部类,后面部分还可以这样

    1 if __name__ == '__main__':
    2     p = parent()
    3     p.getName()
    4     c =  p.child()
    5     c.getName()
    杨河
  • 相关阅读:
    composer npm bower 版本依赖符号说明
    FastAdmin 速极后台框架从 v1.0 到 v1.2 的数据库升级
    FastAdmin 也可以出书了
    FastAdmin 开发时用到的 Git 命令 (2020-09-26)
    FastAdmin用什么弹窗组件
    笔记:Linux 文件权限
    笔记:使用源代码在 Centos 7 安装 Git 2
    php gd 生成表格 图片
    easyui datagrid 清空
    mysql 去重
  • 原文地址:https://www.cnblogs.com/yang-he/p/11493747.html
Copyright © 2020-2023  润新知