我有一个带有更新其对象属性的函数的类。我想弄清楚哪个更 pythonic:我应该明确返回我正在更新的对象,还是简单地更新 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)
我环顾四周,但没有看到任何明确的答案。
编辑:具体来说,我正在寻找可读性和执行时间。两种功能在任一类别中都有优势吗?
最佳答案
我认为第一种情况在任何语言中都不会被认为是好的。
尝试了解该方法的目的是什么。如果目的是修改对象的状态,那么一定要修改它。如果目的是为调用者提供有用的信息,则返回该值。
关于python - 最好在 Python 中返回或更新对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035688/