返回值与在Python中直接设置属性的方法的方法

D K*_*D K 4 python oop coding-style

以下哪个类将演示设置实例属性的最佳方法?它们应该根据情况互换使用吗?

class Eggs(object):

    def __init__(self):
        self.load_spam()

    def load_spam(self):
        # Lots of code here
        self.spam = 5
Run Code Online (Sandbox Code Playgroud)

要么

class Eggs(object):

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

    def load_spam(self):
        # Lots of code here
        return 5
Run Code Online (Sandbox Code Playgroud)

Joh*_*nes 9

我更喜欢第二种方法.

原因如下:带副作用的程序往往会引入时间耦合.简而言之,更改执行这些过程的顺序可能会破坏您的代码.返回值并将它们传递给需要它们的其他方法会使方法间通信显式化,从而更容易推理并且难以忘记/得到错误的顺序.

还返回一个值可以更容易地测试您的方法.使用返回值,您可以将封闭对象视为黑盒子并忽略对象的内部,这通常是一件好事.它使您的测试代码更加健壮.