您的位置:首页 > 编程语言 > Python开发

我想要的 python 特性

2010-11-29 18:52 190 查看
赖勇浩(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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: