1

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 :(
Maximus93
  • 29
  • 3
  • You cannot change the identity of an object, if that is what you are asking. You can *mutate* your object to have *the same relevant values*, in this case, reset would simply do `self.number=2`. But why isn't `mode = Model(2)` what you need, precisely? – juanpa.arrivillaga Jun 19 '20 at 09:16
  • You just ended up assigning newly created instance to a local variable `self`. You cannot replace object with another object in-place. You `reset` should really just set the instance to its desired / initial state by setting its attributes. – Ondrej K. Jun 19 '20 at 09:16

3 Answers3

2

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

dvec
  • 327
  • 4
  • 10
1

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
Maximus93
  • 29
  • 3
0

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
timgeb
  • 76,762
  • 20
  • 123
  • 145