首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类别和列表(自动售货机)

类别和列表(自动售货机)
EN

Stack Overflow用户
提问于 2019-05-09 06:43:20
回答 1查看 356关注 0票数 0

我创建了一些代码来模拟自动售货机,我想知道机器里有什么,但我无法做到这一点。

这是我在打印(机器)时的输出:

代码语言:javascript
复制
[<__main__.Vending_slot object at 0x7fd59f53db38>,
 <__main__.Vending_slot object at 0x7fd59f53dba8>,
 <__main__.Vending_slot object at 0x7fd59f53db00>,
 <__main__.Vending_slot object at 0x7fd59f53dbe0>]

代码:

代码语言:javascript
复制
class Vending_slot:

    def __init__(self, product, stock, price):
        self.product = product
        self.stock = stock
        self.price = price

    def dispense_item(self):
        print(f"You bought a {self.items[0]}.")
        self.items = items[1] 


machine = []
machine.append(Vending_slot("A1", ["Coke","Coke","Coke"], 1.5))
machine.append(Vending_slot("A2", ["Water","Water","Water"], 0.5))
machine.append(Vending_slot("B1", ["Twix","Twix","Twix"], 1))
machine.append(Vending_slot("B2", ["Gum","Gum","Gum"], 0.8))

print(machine)
EN

回答 1

Stack Overflow用户

发布于 2019-05-09 06:55:55

在使用print时,需要实现__repr__方法才能看到Vendind_slot的属性。将此代码添加到您的类中:

代码语言:javascript
复制
def __repr__(self):
    return f"{self.product} {self.stock} {self.price}"

print(machine)的输出将为:

代码语言:javascript
复制
[A1 ['Coke', 'Coke', 'Coke'] 1.5,
 A2 ['Water', 'Water', 'Water'] 0.5,
 B1 ['Twix', 'Twix', 'Twix'] 1,
 B2 ['Gum', 'Gum', 'Gum'] 0.8]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56049983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档