任何人都可以通过调用“ self.init (”来解释重新初始化对象是否安全。如以下简化示例所示?
我问的原因是我在几本python书籍和互联网上都找不到这种方法。有人建议列出所有属性,并一一设置为初始值。基本上我想在完成一些任务后将我的对象设置为初始状态。
class Book(object):
def __init__(self,name,author):
self.name = name
self.author = author
self.copies = 5
def reset(self):
self.__init__(self.name,self.author)
def incrementCopy(self):
self.copies += 1
Kite = Book('kite runner','khaled hosseini')
print 'initial number of copies:', Kite.copies
Kite.incrementCopy()
Kite.incrementCopy()
Kite.incrementCopy()
print '3 copies are added:', Kite.copies
Kite.reset()
print 'number of copies are reinitialized', Kite.copies
initial number of copies: 5
3 copies are added: 8
number of copies are reinitialized 5