PythonCrashCourse第151页。 TypeError:无法连接'str'和'NoneType'对象

时间:2017-01-22 18:17:24

标签: python

在我的书中,Python Crash Course:给出了这段代码,但它给出了一个错误。

def make_pizza(*toppings):
    """Summarize the pizza we are about to make."""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(make_pizza("peperoni"))

make_pizza(make_pizza("mushroom",'green peppers','extra cheese'))

回溯如下:

print(“ - ”+ topping)

TypeError:无法连接'str'和'NoneType'对象

问。这里的NoneType对象是什么?它是打顶?如果是,为什么?

即使我在str()周围使用topping,它也会给我一个有趣的输出:

def make_pizza(*toppings):
"""Summarize the pizza we are about to make."""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
    print("- " + str(topping))

make_pizza(make_pizza("peperoni"))
make_pizza(make_pizza("mushroom",'green peppers','extra cheese'))

输出

Making a pizza with the following toppings:

- peperoni

Making a pizza with the following toppings: 

- None

Making a pizza with the following toppings:
- mushroom
- green peppers
- extra cheese

Making a pizza with the following toppings:
- None

Q2。为什么每个都显示2个输出? - 一个与浇头列表 - 一个没有?

1 个答案:

答案 0 :(得分:1)

你不应该把这个功能传递给自己。

替换这些:

modelBuilder.Entity<House>()
    .HasOptional(e => e.Garage)
    .WithOptionalDependent(e => e.House)
    .Map(m => m.MapKey("GarageId"));

make_pizza(make_pizza("peperoni"))
make_pizza(make_pizza("mushroom",'green peppers','extra cheese'))

发生错误的原因是因为您将函数make_pizza("peperoni") make_pizza("mushroom",'green peppers','extra cheese') 传递给自身,该函数没有return值(它不返回任何内容)。

然而,内部函数仍然完全执行。也就是说,每个示例中的第二个make_pizza运行正常,这就是您获得两个输出的原因。

对于第二个功能,您可以有效地尝试运行:

make_pizza

这当然会导致错误:

make_pizza(None)

因为print("- " + topping) topping

您有时在输出中看到None的原因是因为- Nonestr(None)转换为None(例如,包含文字文本"None"的字符串)。