Python:类似jQuery的函数链接? [英] Python: jQuery-like function chaining?
问题描述
我无法在Google上找到关于此主题的任何内容,因此我认为我应该在此处询问:
是否可以使用Python链接函数,如jQuery是否?
['my','list']。foo1(arg1,arg2).foo2(arg1,arg2)。 foo3(arg1,arg2)#etc ...
当我失去很多空间和可读性时我写这段代码:
foo3(foo2(foo1(['my','list'],arg1,arg2), arg1,arg2),arg1,arg2)#etc ...
似乎存在一些虚幻的库创建这样的功能,但我似乎无法看到为什么这必须是如此复杂 - 看... ...
谢谢!
以下是Simon的 ListMutator
建议的扩展:
class ListMutator(object):
$ b $ def __init __(self,seq):
self.data = seq
def foo1(self,arg1,arg2):
self.data = [x + arg1 for x in self.data]
#这允许链接:
返回self
def foo2(self,arg1,arg2):
self.data = [x * arg1 for x in self.data]
return self
if __name__ ==__main__:
lm = ListMutator([1, 2,3,4])
lm.foo1(2,0).foo2(10,0)
print lm.data
#或者,如果您确实必须:
print ListMutator([1,2,3,4])。foo1(2,0).foo2(10,0).data
您可以更好地使用< code> ListMutator 完全像列表一样使用集合抽象基类。事实上,你可以继承 list
本身,尽管它可能会限制你做某些事情,你可能需要做的事情......我不知道一般意见是什么在子类化内置类型,如 list
。
I couldn't find anything on this subject on Google, so I think I should ask it here:
Is it possible to chain functions with Python, like jQuery does?
['my', 'list'].foo1(arg1, arg2).foo2(arg1, arg2).foo3(arg1, arg2) #etc...
I am losing a lot of space and readability when I write this code:
foo3(foo2(foo1(['my', 'list'], arg1, arg2), arg1, arg2), arg1, arg2) #etc...
There seems to exist some illusive library for creating such functions, but I can't seem to see why this has to be so complicated-looking...
Thanks!
Here's an expansion of Simon's ListMutator
suggestion:
class ListMutator(object):
def __init__(self, seq):
self.data = seq
def foo1(self, arg1, arg2):
self.data = [x + arg1 for x in self.data]
# This allows chaining:
return self
def foo2(self, arg1, arg2):
self.data = [x*arg1 for x in self.data]
return self
if __name__ == "__main__":
lm = ListMutator([1,2,3,4])
lm.foo1(2, 0).foo2(10, 0)
print lm.data
# Or, if you really must:
print ListMutator([1,2,3,4]).foo1(2, 0).foo2(10, 0).data
You could go one better and make ListMutator
act entirely like a list by using the collections abstract base classes. In fact, you could subclass list
itself, although it may restrict you from doing certain things you might need to do... and I don't know what the general opinion is on subclassing built-in types like list
.
这篇关于Python:类似jQuery的函数链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!