gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:53 26 4
gpt4 key购买 nike

属性是存储食品的列表。

这是我以前做过的类(class)食物

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():返回代表股票名称的字符串列表库存中的所有食品。

– load(food):将食物对象添加到库存中。

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())

我应该得到[“香蕉”,“苹果”,“酸奶”,“苹果”]

哪一部分是错误的???

最佳答案

您仍然应该有一个 __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"]

关于python - 使用不带参数的构造函数编写类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22879427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com