简体   繁体   English

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

[英]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. 如果有疑问,我会选择第二个版本,因为它更明确,load_spam没有(或至少更少)副作用。 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. 如果要设置实例属性,则第一种方法更多是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! 请注意,第二种方法不仅不是Pythonic,它具有误导性 - 它被称为load_spam ,但它没有!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM