赖勇浩(http://laiyonghao.com) 一些异想天开,但有些的确是能减轻编码任务的,欢迎大家探讨。 1、callable seq def foo():print 'hello, world.' def bar(arg):print 'hello, %s.'%str(arg) var = [foo] var() # output: hello, world. var = [bar] var('lai') # output: hello, lai. var = [bar, 'lai']() # output: hello, lai. def bar(arg, param):print '%s, %s.'%(arg, param) var = [bar] var.bind('hello') var('world') # output: hello, world. try: var.bind(xx = 'world') except BindError, e: print 'bind failed.', str(e) 2、singleton object def AClass(object):pass #新关键字 instance instance AInstance(AClass): # 新内置方法 __inst__ def __inst__(self): pass def instance_method(self, arg, param): pass def instance_method2(self, arg, param): pass 单件,初始化时调用 __inst__ 方法。相当于以下代码: class AClass(object):pass def instance_method(self, arg, param): pass def instance_method2(self, arg, param): pass AInstance = AClass() import new AInstance.instance_method = new.instancemethod(instance_method, AInstance, AClass) AInstance.instance_method2 = new.instancemethod(instance_method2, AInstance, AClass) __inst__(AInstance) # 初始化 3、message oriented programming class Foo(object): def greet(self, name): print 'hello, %s.'%str(name) class Bar(object): def __init__(self, name): self.name = name foo = Foo() message.sub('hello', foo.greet) bar = Bar('lai') message.pub('hello', bar.name) # output: hello, lai. message.unsub('hello', foo.greet) try: message.pub('hello', bar.name) except NoSubscriberError, e: pass # 不抛 NoSubscriberError 异常的安静模式 message.pub_q('hello', bar.name)
posted on 2010-11-29 18:52 哼哼唧唧 阅读(82) 评论(0) 编辑 收藏 举报