【问题标题】:Did not get expect result- Python没有得到预期的结果 - Python
【发布时间】: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_restaurantopen_restaurant 中使用打印语句,让它返回一个字符串。

标签: python python-3.x function class


【解决方案1】:

describe_restaurant 是一个函数。当你写

print(p.describe_restaurant)

你得到一个函数的字符串表示。然而,你想调用这个函数,让它执行,并打印它的返回值。为此,请通过添加括号来调用它:

p.describe_restaurant()

此外,请确保实际调用您的 test 方法,如下所示:

test()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-13
相关资源
最近更新 更多