zhufeng518 发表于 2017-4-30 14:26:08

我想要的 python 特性

  赖勇浩(http://laiyonghao.com)
一些异想天开,但有些的确是能减轻编码任务的,欢迎大家探讨。
1、callable seq
def foo():print 'hello, world.'def bar(arg):print 'hello, %s.'%str(arg)var = var()# output: hello, world.var = var('lai')# output: hello, lai.var = ()# output: hello, lai.def bar(arg, param):print '%s, %s.'%(arg, param)var = 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#新关键字 instanceinstance AInstance(AClass):# 新内置方法 __inst__def __inst__(self):passdef instance_method(self, arg, param):passdef instance_method2(self, arg, param):pass
单件,初始化时调用 __inst__ 方法。相当于以下代码:
class AClass(object):passdef instance_method(self, arg, param):passdef instance_method2(self, arg, param):passAInstance = AClass()import newAInstance.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 = namefoo = 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)
页: [1]
查看完整版本: 我想要的 python 特性