如何在Python中制作递归函数?

问题描述 投票:0回答:1

我正在尝试创建一个简短的 python 3 函数,它接受 2 类物品并输出库存列表。一个类只是普通对象(我们将其称为“项目”类),另一个类是包含其他对象的对象(我将它们称为“容器”)。当我尝试打印清单中的每个对象(两个类)时,问题就出现了。这包括容器内的物品。它应该看起来像这样:

You are carrying:
an apple
a basket, containing:
 an orange
 a glass bottle, containing:
  a quantity of water

我当前的代码基本上手动执行此操作:

if(object.type=='container'):
 for object1 in object.inventory:
  print(object.name)
  if(object1.type=='container'):
   for object2 in object1:
    print(object2.name)

等等,这显然是残暴的。我怎样才能让这个函数在理论上是无限的?

-我是 python 新手,所以对解决方案的简单解释总是值得赞赏的!-

python python-3.x
1个回答
0
投票

像下面这样的东西应该可以工作。我避免使用术语“对象”,因为这是 Python 中内置的术语,因此有点保留。

此外,你有两个变体:

for ... in object.inventory
for ... in object1
,所以我不确定你的东西到底是如何嵌套的。如果需要,请调整代码。

def print_items(container):
    for item in container:
        print(item)
        if item.type == "container":
            print_items(item)  # the next iterable should go in here


# then use the function on the outermost container
print_items(outermost_container)
© www.soinside.com 2019 - 2024. All rights reserved.