Skip to main content
 首页 » 编程设计

python之在python中的同一个类的定义中创建一个类的实例

2025年05月04日13tuyile006

我正在尝试在 MyClass 的定义中创建一个新的 MyClass 实例。

为什么这段代码会失败,如何实现?

class MyClass: 
        def __init__(self): 
                self.child=MyClass() 
 
mc=MyClass() 

请您参考如下方法:

嗯,它失败了,因为它有无限递归。想一想,如果每个 MyClass 都有一个 child 是 MyClass,它会一直持续下去!

您可以通过多种方式解决此问题。首先,您可以为构造函数提供一个参数:

class MyClass: 
   def __init__(self, create = True): 
      if create: 
         self.child = MyClass(False) 
 
mc = MyClass() 

或者,您可以使用另一种外部方法:

class MyClass: 
    def set_child(self,child = None): 
        # I prefer to make child optional for ease of use. 
        child = MyClass() if child is None else child 
        self.child=child 
 
mc=MyClass() 
mc.set_child() 

我个人更喜欢第一种解决方案,因为它意味着外部对象不需要了解类的任何信息。当然,您可以将两者结合起来:

class MyClass: 
    def __init__(self, create): 
        if create: 
            self.set_child(create=False) 
 
    def set_child(self,child = None, create = True): 
        child = MyClass(create) if child is None else child 
        self.child=child 
 
mc=MyClass() 

这样 mc 默认有一个 child ,您可以随时选择设置 child 。

然后还有“让我们创建某个数字”的方法:

class MyClass: 
    def __init__(self, count = 10): 
        count -= 1 
        if count: 
           # the first child gets the value 9. 
           # the second gets 8. 
           # when the count gets to 0, stop! 
           self.child = MyClass(count) 

旁白:如果你想得到一个对象的类,你可以使用值obj.__class__。这将在上面的所有示例中输出 MyClass。