In. NET and Java, we have seen the implementation of Nested classes. As a local tool for external classes, it is still very useful. Today we have seen great support in Python. The implementation of Nested classes in dynamic languages is worth learning. It should be said that nested classes solve design problems while simplifying programs.
#!/usr/bin/env pythonimport threading, sysdef nested1(timeout): def _1(function): def _2(*args,**kw): class child(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result=None self.error = None self.setDaemon(True) self.start() def run(self): try: self.result = function(*args, **kw) except: self.error = sys.exc_info() c = child() c.join(timeout) if c.isAlive(): raise TimeoutError, 'took too long' if c.error: raise c.error[0], c.error[1] return c.result return _2 return _1def test(a, b): for i in xrange(100000): a = a+b return aif __name__ == '__main__': nested1 = nested1(2) nested2 = nested1(test) print nested2(2,3) a = nested2.child() print a
The above is a reference for web. in an example of The py framework, the print a section below is my test. I found that the function object cannot reference the internal class. The implementation here can find that much less code than writing multiple functions and classes independently.
Let's look at another example:
#!/usr/bin/env pythonimport os, sysclass parent: def __init__(self): self.name = 'parent' def getName(self): print self.name class child: def __init__(self): self.name = 'child' def getName(self): print self.nameif __name__ == '__main__': child = parent.child() child.getName()
Here, the internal class is referenced from the parent class, and the latter part can be as follows:
if __name__ == '__main__': p = parent() p.getName() c = p.child() c.getName()