最好在Python中返回或更新对象属性?

2024-05-13 00:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类,它有一个更新其对象属性的函数。我想弄清楚哪个更像python:我应该显式地返回正在更新的对象,还是简单地更新self对象?在

例如:

class A(object):

    def __init__(self):
        self.value = 0

    def explicit_value_update(self, other_value):
        # Expect a lot of computation here - not simply a setter
        new_value = other_value * 2
        return new_value

    def implicit_value_update(self, other_value):
        # Expect a lot of computation here - not simply a setter
        new_value = other_value * 2
        self.value = new_value
        #  hidden `return None` statement

if __name__ == '__main__':
    a = A()
    a.value = a.explicit_value_update(2)
    a.implicit_value_update(2)

我到处看看,但没有看到任何明确的答案。在

编辑:具体来说,我在寻找可读性和执行时间。这两种功能在这两种类型中都有优势吗?在


Tags: of对象selfnewherevaluedefnot
2条回答
a.value = a.explicit_value_update(2)

在我看来很奇怪。在

您的..._update方法都没有self参数,因此无法正常工作。explicit_value_update不使用任何属性,因此应该是@staticmethod。在

^{pr2}$

这使得它的功能与类相关,但不需要访问类或实例属性。在

但我认为最好的办法是使用房产:

class A(object):

    def __init__(self):
        self.value = 0

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, other_value):
        self._value = 2 * other_value

if __name__ == '__main__':
    a = A()
    a.value = 2
    print a.value # 4

注意,现在没有样板文件了—您只需直接指定给属性,setter会为您处理它。Python中的传统做法是从修改对象的方法返回对象。在

我不认为第一个案例会被认为是好的任何语言。在

试着理解这个方法的目的是什么。如果目的是修改对象的状态,那么一定要修改它。如果目的是为调用者提供有用的信息,则返回值。在

相关问题 更多 >