【发布时间】:2017-05-06 06:04:25
【问题描述】:
为什么我不能得到结果(肯德基是一家美式餐厅)?怎么改?符合要求吗?
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)
【问题讨论】:
-
那是因为
p是在t中定义的,所以它超出了范围。您可以将其作为参数传递(h(p)) -
@t.m.adam 已完美回复。如果我可以补充一下,另一个响应建议全局变量,这些变量通常不被认为是任何编程语言的最佳实践。此外,根据您的代码要求,您似乎根本不需要两个单独的函数。单一功能“测试”应充分满足附件中提到的要求。此外,打印 p.describe_restaurant 的返回值的调用将失败,因为 describe_restaurant() 没有返回值。只需调用 p.describe_restaurant()。
-
我不会在
describe_restaurant和open_restaurant中使用打印语句,让它返回一个字符串。
标签: python python-3.x function class