create instance of a class in the same class's definition in python -
I am trying to create a new MyClass instance in the definition of MyClass.
Why does this code fail and how can it get it?
class MyClass: def __init __ (self): self.child = MyClass () mc = MyClass ()
Well, it fails because there's infinite recursion in it, think about it, if every micellus has a child who is a myclass, then it's infinity Will be!
You can solve it in some ways First of all, you can have a parameter for the creator:
class MyClass: def __init __ = True): If created: self.child = MyClass (wrong) MC = MyClass () Or, you can have another, external method:
class MyClass: def set_child (self, children = none): # I like to make a child alternative child = Miklash () for ease of use. If there is a child then there is no other child. Children = Baby mc = MyClass () mc.set_child () I personally prefer the first solution because it means that external objects do not need to know anything about the class Of course, you can add two:
class MyClass: def __init __ (self, create): if created: self.set_child (create = false) def set_child (self, child = None, Build = true): Children = MyClass (Create) If the child is none other child self.child = child mc = MyClass () Just a child and you have
class MyClass: def __init __ (self, count ===================== ================================================== =========== <10): Calculation - = 1 if count: # First child gets value 9. # Second becomes 8. # When the count is 0, stop! Self. Child = Miles (Count)
On the one hand: If you want to get the object's class, then you use the value obj .__ class __ can do. This will produce MyClass in all the above examples.
Comments
Post a Comment