在类中返回元组列表

2024-10-02 04:25:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在类中生成返回元组

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 witchexecutemany中做insert,怎么都没有interator不工作。你知道吗

实现类:

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


Tags: nameimageselfreturninitvaluedefmysql
1条回答
网友
1楼 · 发布于 2024-10-02 04:25:15

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

相关问题 更多 >

    热门问题