Python将对象元素追加到for循环列表中,获取重复元素?

时间:2017-10-27 11:06:50

标签: python for-loop

我是Python的新手。我想在for循环中添加对象列表。但我得到重复的元素。这是代码。

import pymysql
import dbUtil

db = pymysql.connect('localhost', 'root', 'password', 'nzdlfc')

cursor = db.cursor()


class Video:
    def __init__(self):
        self.title = ''
        self.time = ''
        self.category = ''
        self.url = ''
        self.id = ''


def getVideoInfo():

    ls = dbUtil.get_data_tuple_ls("SELECT * FROM VIDEO")
    video_ls = []
    for i in ls:
        video_obj = Video
        video_obj.id = i[0]
        video_obj.title = i[1]
        video_obj.time = i[2]
        video_obj.category = i[4]
        video_obj.url = i[7]
        video_ls.append(video_obj)

    return video_ls


videoObj_ls = getVideoInfo()

for j in videoObj_ls:
    print(j.id)
    print(j.title)
    print(j.time)
    print(j.category)
    print(j.url)

我在DB中有4个元素,但是当我打印videoObj_ls时,我得到4个第四个元素。任何人都可以指导我解决这个问题。非常感谢。

1 个答案:

答案 0 :(得分:2)

你已经在khelwood的评论中得到了解决方案 - 作为更一般的答案,如果你没有明确地应用呼叫运算符,则不会调用callables(类,函数,方法等),Iow the parens

作为旁注:您可以直接将所有值传递给Video类初始值设定项,并将SQL查询限制在实际使用的字段中,从而受益:

class Video:
    def __init__(self, id, title, time, category, url):
        self.id = id
        self.title = title
        self.time = time
        self.category = category
        self.url = url


def getVideoInfo():
    # I assume the db fields have the same names as 
    # the class attributes - else fix this with the 
    # right field names
    sql = "SELECT id, title, timen category, url FROM VIDEO"
    ls = dbUtil.get_data_tuple_ls(sql)
    video_ls = [Video(*row) for row in ls]
    return video_ls