reinitialize an object with self.__init__(...)

Posted by Kara Jevo on Stack Overflow See other posts from Stack Overflow or by Kara Jevo
Published on 2012-10-26T16:58:32Z Indexed on 2012/10/26 17:00 UTC
Read the original article Hit count: 241

Filed under:

Could anybody explain whether it is safe to reinitialize an object by calling "self.init(". as shown in the following simplified example?

The reason i'm asking is that i couldn't find this method neither in several python books nor in internet. There are some who suggest to list all attributes and set them to initial value one by one. Basically i want to set my object to initial state after it has finished some tasks.

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

© Stack Overflow or respective owner

Related posts about python