使用不带参数的构造函数编写类

时间:2014-04-05 10:08:52

标签: python

属性是存储食物项目的列表。

这是我以前做过的食品类

class Food(object):
    def __init__(self,name,nutrition,good_until):
        self.name = name
        self.nutrition = nutrition
        self.good_until = good_until
        self.age = 0

方法:

- 构造函数不参数。

- get_stock_names():返回表示名称的字符串列表 库存中的所有食品。

- 装载(食物):将食物添加到库存中。

class VendingMachine(object):
    def load(self,food):
        self.food = food
        return self.food
    def get_stock_names(self):
        self.obj = []
        self.obj.append(self.load())


machine = VendingMachine()
apple = Food("apple", 70, 7)
banana = Food("banana", 100, 4)
yoghurt = FermentedFood("yoghurt", 50, 0, 10)
machine.load(banana)
machine.load(apple)
machine.load(yoghurt)
machine.load(apple)
print(machine.get_stock_names())  

我应该["banana", "apple", "yoghurt", "apple"]

哪个部分错了?

1 个答案:

答案 0 :(得分:1)

您仍然应该使用__init__方法初始化变量,如下所示:

class VendingMachine(object):
    def __init__(self):
        self.foods = []

    def load(self,food):
        self.foods.append(food)
        return self.foods

    def get_stock_names(self):
        return [i.name for i in self.foods]

machine = VendingMachine()
apple = Food("apple", 70, 7)
banana = Food("banana", 100, 4)
yoghurt = FermentedFood("yoghurt", 50, 0, 10)
machine.load(banana)
machine.load(apple)
machine.load(yoghurt)
machine.load(apple)
print(machine.get_stock_names())
["banana", "apple", "yoghurt", "apple"]