Igor Alex
Igor Alex

Reputation: 1121

How to properly reinitialise python object?

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?

Upvotes: 2

Views: 1467

Answers (2)

Giorgos Myrianthous
Giorgos Myrianthous

Reputation: 39910

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

Upvotes: 3

totok
totok

Reputation: 1500

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.

Upvotes: 1

Related Questions