freude
freude

Reputation: 3832

multiple initialization of the same object in python

I have several noobie questions related to multiple initialization of the same class instance in python. Is it proper way to change attributes of the object by creating instance many times:

obj=MyClass(a,b)
obj=MyClass(c,d)
obj=MyClass(e,f)

Are commands obj=MyClass(a,b) and obj.__init__(a,b) equal? If not, what is the difference?

Upvotes: 0

Views: 1993

Answers (2)

Nicola Musatti
Nicola Musatti

Reputation: 18218

In your example you're instantiating three different objects of class MyClass and discarding the first two. In order to be able to perform the same initialization several times on the same object I'd define an initialize(self) method in MyClass and call it from __init__(self).

Upvotes: 3

Andrew
Andrew

Reputation: 24846

obj = MyClass(a,b) - this will create a new instance

obj.__init__(a,b) - this will call __init__ method with on the current instance

Usually you call __init__ implicit once, when creating an instance (obj = MyClass(a,b)) and modify it's fields later directly or using some methods. Like:

obj = MyClass(a,b)
obj.a = 'foo'
obj.b = 2

Upvotes: 1

Related Questions