Python: jQuery-like function chaining?

前端 未结 5 1012
面向向阳花
面向向阳花 2020-12-30 11:47

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?



        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 12:25

    As long as the function returns a value, you can chain it. In jQuery, a selector method usually returns the selector itself, which is what allows you to do the chaining. If you want to implement chaining in python, you could do something like this:

    class RoboPuppy:
    
      def bark(self):
        print "Yip!"
        return self
    
      def growl(self):
        print "Grr!"
        return self
    
    pup = RoboPuppy()
    pup.bark().growl().bark()  # Yip! Grr! Yip!
    

    Your problem, however, seems to be that your function arguments are too cramped. Chaining is not a solution to this. If you want to condense your function arguments, just assign the arguments to variables before passing them to the function, like this:

    spam = foo(arg1, arg2)
    eggs = bar(spam, arg1, arg2)
    ham = foobar(eggs, args)
    

提交回复
热议问题