【发布时间】:2023-03-19 23:50:01
【问题描述】:
我有Animal类和两个Child类Fish和Bear
class Fish(Animal):
def __init__(self, x, y, parent_engine):
self.parent = parent_engine
self.x = x
self.y = y
self.type = 2
self.image = '????'
self.life = 1
class Bear(Animal):
def __init__(self, x, y, parent_engine):
self.parent = parent_engine
self.x = x
self.y = y
self.type = 3
self.image = '????'
self.life = 1
在代码中,我有一个名为 Field
的 Animal type 对象数组class Engine:
def __init__(self, size):
self.field = []
self.field_size = size
我有函数 create_actor_child 和输入 actor (Animal object)。这个函数应该用相同的子类创建新的Animal。我正在使用 if - watch is Parent Bear - 生成熊,否则生成鱼。但是,如果我要生 10 个孩子,那就很难了。我认为应该有解决方案来创建父类的新副本。
def create_actors_child(self, actors): # returns parents back
sample = actors[0]
x = sample.x
y = sample.y
for actor in actors:
actor.go_back_event()
if sample.type == 2:
self.field.append(bp.Fish(x, y, self))
else:
self.field.append(bp.Bear(x, y, self))
我需要像self.field.append(parent_class(actor)) 这样的东西。
在 Python 中是否有一种简单的方法可以做到这一点,还是我需要创建自己的方法?
【问题讨论】:
标签: python arrays class parent-child