I have written a chainable API (in a similar style to jQuery) as follows:
class ChainableAPI:
def show(self):
self.visibility = 1
return self
def goBlue(self):
self.color = 'Blue'
return self
def die(self):
self.life = 0
return self
chainableAPI = ChainableAPI()
(chainableAPI
.goBlue()
.show()
.die()
.goBlue())
Notice how each method of ChainableAPI ends with return self. Is there a way to have all methods to return self automatically? That way I do not have to specify return self manually for each method.
You could use a decorator:
Then the class would look like this:
But is it better than just writing
return self?Also, a class decorator could be written to apply the
chainabledecorator to all methods not starting with_:Example:
Still, no matter how cool it may be I still think you should just use
return self. But this shows how powerfull Python is.