I am trying to create a new MyClass instance in MyClass’s definition.
Why does this code fail and how can achieve it?
class MyClass:
def __init__(self):
self.child=MyClass()
mc=MyClass()
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, it fails because it has infinite recursion. Think about it, if every MyClass has a child which is a MyClass, it will go on for infinity!
You can resolve this a couple of ways. First, you can have a parameter to the constructor:
Or, you can have another, external method:
I personally prefer the first solution as it means that outside objects don’t need to know anything about the class. Of course, you could combine the two:
This way mc has a child by default and you have the option of setting the child whenever you like.
Then there is also the “let’s create a certain number” approach:
Aside: If you want to get an object’s class, you can use the value
obj.__class__. That will output MyClass in all of the examples above.