解决方法是使用工厂模式或者原型模式来避免在子对象的创建中重复使用构造函数。
class Parent:
def __init__(self, name):
self.name = name
class Child:
def __init__(self, parent):
self.parent = parent
class ChildFactory:
def create_child(self, parent_name):
parent = Parent(parent_name)
child = Child(parent)
return child
# 使用工厂模式创建子对象
factory = ChildFactory()
child1 = factory.create_child("Parent 1")
child2 = factory.create_child("Parent 2")
import copy
class Parent:
def __init__(self, name):
self.name = name
class Child:
def __init__(self, parent):
self.parent = parent
def clone(self):
return copy.deepcopy(self)
# 创建原型对象
parent = Parent("Parent")
# 使用原型对象创建子对象
child1 = Child(parent.clone())
child2 = Child(parent.clone())
这样,每次创建子对象时都会使用新的父对象,避免了重复使用构造函数的问题。