Should internal class methods return values or just modify instance variables?

后端 未结 4 957
感情败类
感情败类 2020-12-14 06:55

I am creating a query builder class that will help in constructing a query for mongodb from URL params. I have never done much object oriented programming, or designed clas

4条回答
  •  春和景丽
    2020-12-14 07:25

    If you return anything at all, I'd suggest self. Returning self from instance methods is convenient for method chaining, since each return value allows another method call on the same object:

    foo.add_thing(x).add_thing(y).set_goal(42).execute()
    

    This is sometimes referred to as a "fluent" API.

    However, while Python allows method chaining for immutable types such as int and str, it does not provide it for methods of mutable containers such as list and set—by design—so it is arguably not "Pythonic" to do it for your own mutable type. Still, lots of Python libraries do have "fluent" APIs.

    A downside is that such an API can make debugging harder. Since you execute the whole statement or none of it, you can't easily see the object at intermediate points within the statement. Of course, I usually find print perfectly adequate for debugging Python code, so I'd just throw a print in any method whose return value I was interested in!

提交回复
热议问题