Return self in class method - is this good approach?

class, oop, python, self

Solution

Is it really how it works?

No, it won't create a new object, it will return the same instance. You can check it by using `is` keyword, which checks if two objects are the same:

t = TestClass(3)
c = t.method_a(4)

print t is c
>>> True

Is it good practice to use return self in python methods?

Yes, it's often used to allow chaining.

Problem

I have a class like below ``` class TestClass(object): def __init__(self, data): self.data = data def method_a(self, data): self.data += data/2 return self def method_b(self, data): self.data += data return self def method_c(self, data): self.data -= data return self ``` Every method returns self. I wrote it that way to be albe to call few metohds in a chain, ie. `object.method_a(10).method_b(12).method_c(11)`. I was told that `return self` in method doesn't return current object, but creates new one. Is it really how it works? Is it good practice to use `return self` in python methods?

Original source

Related problems