method chaining in python

前端 未结 4 554
故里飘歌
故里飘歌 2020-12-07 17:56

(not to be confused with itertools.chain)

I was reading the following: http://en.wikipedia.org/wiki/Method_chaining

My question is: what is the best

4条回答
  •  难免孤独
    2020-12-07 18:44

    I was looking for something similar for chaining Class functions and found no good answer, so here is what I did and thought was a very simple way of chaining: Simply return the self object.

    So here is my setup:

    Class Car():
        def __init__(self, name=None):
            self.name = name
            self.mode = 'init'
    
        def set_name(self, name):
            self.name = name
            return self
    
        def drive(self):
            self.mode = 'drive'
            return self
    

    And now I can name the car and put it in drive state by calling:

    my_car = Car()
    my_car.set_name('Porche').drive()
    

    Caveat: This only works on the class functions that do not intend to return any data.

    Hope this helps!

提交回复
热议问题