I just started learning OOP in Python and came across interesting problem. In short, it's about running a method in the same line as object is initialised - the proposed solution was to return object after each method which we need to "oneline" that way.
My question is, is there a way to create decorator which will do the same thing?
So instead of defining colour() with return:
class Text:
def __init__(self):
self.i = 5
def colour(self, sth):
self.i = sth
return self
The method would look like that:
@Returning(self)
def colour(self, sth):
self.i = sth
This way of doing that is not only a bit more aesthetically pleasing for me, but it easily informs anyone reading the code about method being able to be one-liner, which I find important.
The issue is, though, that trying to come up with my own poor knowledge on decorators, self parameter wasn't even recognised when passed into it.
selfis always the first argument, you can write a decorator that always returns the first argument.colouris otherwise a one-liner? Nobody calling the method will care.