【问题标题】:preferred way to modify attributes修改属性的首选方式
【发布时间】:2018-07-28 12:08:06
【问题描述】:

我在我的类中使用辅助方法来修改属性,并且可以看到几种方法来做到这一点。以下任何helper 和关联的methods 是否有充分的理由首选或避免?

class Test(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def _x_helper1(self):
        self.x += self.y

    def method1(self):
        # some other code...
        self._x_helper1()

    def _x_helper2(self, y):
        # some other code...
        self.x += y

    def method2(self):
        # some other code...
        self._x_helper2(self.y)

    def _x_helper3(self, y):
        # some other code...
        return y

    def method3(self):
        # some other code...
        self.x += self._x_helper3(self.y)

【问题讨论】:

  • 如果没有适当的上下文,就无法比较这些。如何将代码拆分为方法取决于可读性、可测试性和减少重复。

标签: python oop methods helper


【解决方案1】:

这个例子太抽象了。

只添加obj.x + obj.y 并没有错。如果您需要改变对象的状态,并且您仅基于属性进行变异,请使用

def mutate(self):
    self.x += self.y

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2012-07-03
    • 1970-01-01
    • 2019-09-12
    • 2021-11-25
    • 2012-11-04
    相关资源
    最近更新 更多