0
Can we create an object in constructor in python.. If yes why we need it?
2 Réponses
+ 1
I'm interpreting this question two ways, you tell me which answer works best for you.
A. No, objects aren't created in the constructor, rather, they are created then initialized by the constructor. The necessary space in memory is reserved before the statements within the constructor are executed, and then the constructor is called to fill it in, if necessary. Why do we need this? Well, it's just a better, more organized way of doing things.
B. Yes, you can define variables and create objects within a constructor, even instances of the same class if that's what you want (several container classes use this idea to link nodes together). Here's a basic Java class as an example:
class MyClass{
private MyClass instance;
public MyClass(){}
public MyClass(MyClass param){
instance = param;
}
}
Here's a Python example:
class MyClass:
def __init__(self, param=None): #where param is an instance of MyClass
self.instance = param
Be careful when you do this though. If you write your constructor to create a new instance by itself, it will infinitely call the constructor in a never ending cycle of instantiation until you wind up at a stack overflow error. Doing it like these examples will cut it short.