0

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?

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

obj=MyClass(a,b) calls the function 'init' What else does this do?
@freude allocate memory for a new instance
@Nicola Musatti, ok, I see. Is there difference even if all my attributes are defined inside the function init?
Yes, there is, because they're all referring to self, which is different in each of your example's calls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.