I want to replace the class instance "model" with a new instance. This should happen in a reset function inside the class. I could easily do model = Model(number = 2) outside of the class, but that is not what I need.
The number thing is just an easy example for you. My actual task is totally different. In summary I need to create a new instance with the same name, because I need a new run of the __init__. And this has to happen inside the reset function. I hope you understand what I mean. My reset function does not work unfortunately:
class Model():
def __init__(self, number):
self.number = number
def reset(self):
self = Model(number = 2)
model = Model(number = 1)
print(model.number) #it is 1
model.reset()
print(model.number) #it is 1 aswell, should be 2 :(
3 Answers 3
You can't reassign self iside of your class, but you can do something like that:
class Model():
def __init__(self, number):
self.number = number
def reset(self):
self.__dict__ = Model(number = 2).__dict__
model = Model(number = 1)
print(model.number) #it is 1
model.reset()
print(model.number) #it is 2 :)
Read more about dict attribute here
3 Comments
__init__ method instead?self.number = 2. Note, this breaks shared-key namespace dicts...What about this here? Is it allowed to run the init manual in the reset function?
class Model():
def __init__(self, number):
self.number = number
def reset(self):
self.__init__(2)
model = Model(number = 1)
print(model.number) #it is 1
model.reset()
print(model.number) #it is 2 now
Comments
I want to replace the class instance "model" with a new instance.
All you have to do is to rebind the name model.
Use
model = Model(number=2)
or
model = Model(model.number + 1)
If you want to increment number automatically on instantiation, you could use something like this:
class Model:
counter = 1
def __init__(self):
self.number = Model.counter
Model.counter += 1
self.number=2. But why isn'tmode = Model(2)what you need, precisely?self. You cannot replace object with another object in-place. Youresetshould really just set the instance to its desired / initial state by setting its attributes.