开发者

Methods which return values vs methods which directly set attributes in Python

Which of the following classes would demonstrate the best way to set an instance attribute? Should they be used interchangeably based on the situation?

class Eggs(object):

    def __init__(self):
        self.load_spam()

    def load_spam(self):
        # Lots of code here
        self.spam = 5

or

class Eggs(object):

    def __init__(self):
        self.spam = self.load_spam()

    def load_spam(self)开发者_开发技巧:
        # Lots of code here
        return 5


I would prefer the second method.

Here's why: Procedures with side effects tend to introduce temporal coupling. Simply put, changing the order in which you execute these procedures might break your code. Returning values and passing them to other methods in need of them makes inter-method communication explicit and thus easier to reason about and hard to forget/get in the wrong order.

Also returning a value makes it easier to test your method. With a return value, you can treat the enclosing object as a black box and ignore the internals of the object, which is generally a good thing. It makes your test code more robust.


I would indeed choose depending on the situation. If in doubt, I would choose the second version, because it's more explicit and load_spam as no (or at least less) side effects. Less side effects usually lead to code which is easier to maintain and easier to understand. As you know, there's not rule without exception. But that's the way how I would approach the problem.


If you are setting instance attributes the first method is more Pythonic. If you are calculating intermediate results then function calls are fine. Note that the second method is not only not Pythonic, it's misleading -- it's called load_spam, but it doesn't!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜