赖勇浩(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)
我想要的 python 特性
最新推荐文章于 2025-12-11 20:49:41 发布
本文提出了一些创新的编程技巧,包括简化函数调用、实现单例模式和消息导向编程等,旨在提高编码效率。
747

被折叠的 条评论
为什么被折叠?



