问题描述
假设一个类有一个修改它的内部的方法。应该在返回之前调用自己的方法保存,还是应该在调用修改方法之后保存到调用者显式保存?
示例:
显式调用save:
class Bar(models.Model) :
def set_foo(self,foo):
self.foo = foo
bar = Bar()
bar.set_foo(foobar)
bar.save()
或允许方法调用save:
class Bar(models.Model):
def set_foo(self,foo):
self.foo = foo
self .save()
bar = Bar()
bar.set_foo(foobar)
我正在和django一起工作,但是我想知道在这种情况下是否有最佳做法django或一般情况。
您的API的用户可能会忘记调用.save(),然后拧紧。所以我认为更好地为他打电话给他。对于像Daslch提到的情况,如果有意义,可以定义:
def set_foo(self,foo,skip_save = False )
self.foo = foo
如果不是skip_save:
self.save()
,所以如果她希望(并明确说明),用户可以避免保存。
Suppose a class has a method that modifies it's internals.Should that method call save on itself before returning or should the save be left to the caller to explicitly save after the modifying method has been called?
Example:
Explicitly calling save:
class Bar(models.Model):
def set_foo(self, foo):
self.foo = foo
bar = Bar()
bar.set_foo("foobar")
bar.save()
or allowing method to call save:
class Bar(models.Model):
def set_foo(self, foo):
self.foo = foo
self.save()
bar = Bar()
bar.set_foo("foobar")
I'm working with django, but I was wondering if there was a best practice in django or in general for this situation.
The user of your API might forget to call .save() and then get screwed. So I think its better to call save for him. For cases like those Daslch mentions, if it makes sense, you can define:
def set_foo(self, foo, skip_save=False):
self.foo = foo
if not skip_save:
self.save()
so the user can, if she wishes to (and explicitly states that), avoid the save.
这篇关于修改类方法应该在调用该方法之后保存自身或被称为显性性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!