سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

Returning self does not create a new object.

I'm sure some people will tell you that method chaining is bad. I don't agree that it is necessarily bad. Writing an API that is designed for method chaining is a choice, and if you decide to do it you need to make sure everything works as people expect. But if you decide to do it, then returning self is often the right thing to do. (Sometimes, you may want to return a newly-created object instead. It depends whether you want the chained methods to cumulatively modify the original object or not.)

return self does not create a new object, you were told wrong.

If you want to build an API that supports chaining, returning self is a fine practice. You may want to build a new object instead for a chaining API, but that's not a requirement either.

See Python class method chaining for how the SQLAlchemy library handles chaining with new instances per change. Creating a new object when mutating objects in a chain allows you to re-use partial transformations as a starting point for several new objects with different chained transformations applied.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top