首页 > 解决方案 > 返回类中的元组列表

问题描述

如何在课堂上制作返回元组

class Product:
    def __init__(self, name, value, image):
        self.name = name
        self.value = value
        self.image = image

    def __iter__(self):
        return (self.name, self.value, self.image)

我需要在 MySql 女巫executemany中插入,没有交互器怎么办?

实现类:

from Product import Product

Products = []

Product_name = "Fruit 01"
Product_price = 12.25
Product_image = "src/test.png"

Products.append(Product(
    Product_name,
    Product_price,
    Product_image
))

标签: pythonpython-3.x

解决方案


__iter__方法应该返回一个迭代器。

您可以使用该iter函数从元组创建迭代器:

def __iter__(self):
    return iter((self.name, self.value, self.image))

或使用该yield from语句来实现相同的目的:

def __iter__(self):
    yield from (self.name, self.value, self.image)

推荐阅读