The only thing special about __init__
is that it is called automatically when an instance is created. Other than that it is a normal method, and it is safe to use it to set your object back to its initial state.
That being said, just because it is safe doesn't mean it is a good idea. Other people looking at your code might be confused by it, and it isn't difficult to do everything in a reset
method (that __init__
can even call) to be more explicit about how the method is being used.
I would consider it a very bad practice - you should not __init__
manually (unless calling __init__
of the parent class). Also, passing object's data back to __init__
is somewhat strange.
Why not something like this:
class Book(object):
def __init__(self,name,author):
self.name = name
self.author = author
self.reset()
def reset(self):
self.copies = 5
I consider is not unsafe, I have used it and nothing strange happens in the memory, but take into account that attributes defined in other methods will not be reset. Consider for example:
class Dummy:
def __init__(self):
self.x = 4
def plus_one(self):
self.x += 1
def define_other_variables(self):
self.y = 3
def reset(self):
self.__init__()
D = Dummy()
print(D.x) # 4
# print(D.y) will raise an AttributeError
D.plus_one()
D.plus_one()
# D.y do not exist
D.define_other_variables()
# D.y exist
print(D.x) # 6
D.reset()
print(D.x) # 4
print(D.y) # 3, still exist!!
Then, just remember to define every object in the init function. you could consider bad practice for this reason but I still think is elegant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With