如何在Python列表中的类对象上使用类函数?

时间:2018-10-12 12:08:47

标签: python python-3.x

我想创建一个工具,允许用户输入要存储的餐馆详细信息列表,并在完成后打印出来。

我的代码如下:

#Create restaurant class with restaurant object and describe_restaurant function

class restaurant:
    def __init__(self, n, restaurant_name, cuisine_type):
        self.n = n
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

     def describe_restaurant(self):
        print("{} serves {}".format(restaurant.restaurant_name, restaurant.cuisine_type))

#localplaces will contain the restaurant objects

localplaces = []
n = len(localplaces)
active = True

while active:
    localplaces.append(restaurant(n, input("Restaurant Name: "), input("Cuisine type: ")))
    repeat = input("Do you want to add another item?: ")
    if repeat.strip().lower() in ["n", "no"]:
        active = False
    else:
        while repeat.strip().lower() not in ['y', 'yes', 'n', 'no']:
            repeat = input("Add another item? [y/n]: ")

#loop through localplaces printing the object info as defined by the

for restaurant in localplaces:
    print("\n" + restaurant.describe_restaurant().format)

运行此代码(包括我的输入)时出现以下错误:

Restaurant Name: bobs
Cuisine type: burgers
Do you want to add another item?: n
bobs serves burgers
Traceback (most recent call last):
  File "C:/Users/nicholl/PycharmProjects/untitled/Coordinates.py", line 24, in <module>
    print("\n" + restaurant.describe_restaurant().format)
AttributeError: 'NoneType' object has no attribute 'format'

同时,如果我从.format循环(包括我的输入)中删除了for

Restaurant Name: bobs
Cuisine type: burgers
Do you want to add another item?: n
bobs serves burgers
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/Test/Test11111c.py", line 24, in <module>
    print("\n" + restaurant.describe_restaurant())
TypeError: can only concatenate str (not "NoneType") to str

哪怕给我我认为是返回的describe_restaurant()的信息,这使我感到困惑,但是如果我输入第二家餐厅,我会收到相同的错误,但第二家餐厅除外,但它仍然会像上面那样返回第一家餐厅。

在PyCharm中使用Python 3.7,让我知道是否需要澄清任何内容。

1 个答案:

答案 0 :(得分:4)

您在此函数中引用了func EventsJSON(c *gin.Context) { start := c.PostForm("start") end := c.PostForm("end") es := models.GetEvents(start, end) c.JSON(200, es}) } ,但这是对 class 的引用,该类没有restaurantrestaurant_name属性:

cuisine_type

相反,请使用def describe_restaurant(self): print("{} serves {}".format(restaurant.restaurant_name, restaurant.cuisine_type)) ,它将引用对象本身:

self

其他一些风格技巧:

  • 将您的班级命名为def describe_restaurant(self): print("{} serves {}".format(self.restaurant_name, self.cuisine_type)) ,而不是Restaurant(请参见PEP 8
  • 将您的方法命名为restaurant,而不是describe;该方法是您课程的一部分,上下文应明确表明它与餐厅有关