没有得到期望的结果 - Python
为什么我不能得到结果(肯德基是美国餐馆)?我如何改变它?我是否符合要求?没有得到期望的结果 - Python
class Restaurant:
__name=""
__cuisine=""
def __init__(self,name,cuisine):
self.__name=name
self.__cuisine=cuisine
def describe_restaurant(self):
print(self.__name, " is a ",self.__cuisine ," restarurant.")
def open_restaurant(self):
print(self.__name ," is open.")
def test():
p=Restaurant("KFC","American")
print(p.describe_restaurant)
describe_restaurant
是一个函数。当你写
print(p.describe_restaurant)
你会得到一个函数的字符串表示。然而,你想调用这个函数,让它执行,并打印它的返回值。要做到这一点,通过添加括号称之为:
p.describe_restaurant()
此外,一定要实际调用您的test
方法,像这样:
test()
谢谢你,我修改它,但它仍然无法正常工作。 –
@TianxuZang对我来说很好,还有[ideone](http://ideone.com/Rkq6Pj)。你能否确认你有与[ideone上发布的相同的代码](http://ideone.com/Rkq6Pj)? – phihag
谢谢,它的作品! –
这是因为'p'在't'定义,因此它超出了范围。你可以将它作为参数传递('h(p)') –
@ t.m.adam已经完美回答了。如果我可以补充一点,另一个回应建议的全局变量在任何编程语言中通常都不被认为是最佳实践。此外,根据您的代码要求,看起来您根本不需要有两个单独的函数。单一功能“测试”应该充分满足附件中提到的要求。此外,打印p.describe_restaurant返回值的调用将失败,因为describe_restaurant()没有返回值。仅仅打电话给p.describe_restaurant()。 – YashTD
我不会在'describe_restaurant' en'open_restaurant'中使用print语句,让它返回一个字符串。 – Elmex80s