1

For example, I have this class:

class A:
    def __init__(self):
        self.a = 10

In instance lifetime, I change the value of a to 20

test = A()
test.a = 20

In which way I can properly reinitialize this instance, to make default value?

Is the way with calling __ init__ is good?

Igor Alex
  • 446
  • 5
  • 19

2 Answers2

2

Calling an __init__ would do the trick, but I wouldn't recommend it as it might be harder for other people reading your code to understand quickly what you're trying to do. I would create a reset() function instead:

class A:
    def __init__(self):
        self.a = 10

    def reset(self):
        self.a = 10

And now,

test = A()
test.a = 20
test.reset() # now test.a = 10

In order to avoid code duplication, you can also call the reset() function from your __init__:

class A:
    def __init__(self):
        self.reset()

    def reset(self):
        self.a = 10
Giorgos Myrianthous
  • 30,279
  • 17
  • 114
  • 133
  • I am also thinking like this but, what if logic in the init function is huge, would not it be a very big piece of duplicate code? – Igor Alex Aug 12 '20 at 11:48
  • @IgorAlex Another approach would be to create the `reset()` function and call it in your `__init__`. In that case you won't be duplicating any code. – Giorgos Myrianthous Aug 12 '20 at 11:50
1

Calling __init__ is like calling a second time the constructor in another language. You may not do this.

You could create a method called reset_variables, that would be called in the constructor and that you would be able to call yourself.

totok
  • 1,334
  • 7
  • 26