【发布时间】:2015-11-30 20:51:32
【问题描述】:
我在 Python 中有一个类,它为给定数据训练模型:
class Model(object):
def __init__(self, data):
self.data = data
self.result = None
def train(self):
... some codes for training the model ...
self.result = ...
一旦我创建了一个模型对象,
myModel = Model(myData)
模型没有经过训练。然后我可以调用train方法来发起训练:
myModel.train()
然后myModel.result 将就地更新。
另外,我可以将train 方法重写为:
def train(self):
... some code for training the model ...
result = ...
# avoid update in-place
trainedModel = copy.copy(self)
trainedModel.result = result
return trainedModel
这样,通过调用myTrainedModel = myModel.train()我有了一个新的对象,原来myModel的状态并没有改变。
我的问题是:哪种方法更常用来存储类中方法的返回结果?
【问题讨论】:
-
这真的取决于你想要达到的目标。作为一般规则,如果函数有
result,为什么不采用第三个选项并返回结果?
标签: python class coding-style