1

好的,所以我正在尝试打印所有汽车对象...我有 2 个问题:

  1. 我实施的方式__iter__可以接受吗?
  2. 我现在得到了我想要的结果,但结果相当丑陋......有没有办法格式化打印以使其看起来更漂亮?

这是我的代码:

import sqlite3

class Database:

    def __init__(self, **kwargs):
    self.filename = kwargs.get('filename')

    def __iter__(self):
        car_object = {}
        cursor = self._db.execute('select * from CARS'.format(self._table))
        for row in cursor:
            objectname = str(row['IDENT'])
            car_object[objectname] = Cars(make = row['MAKE'], 
            model = row['MODEL'], disp = row['DISPLACEMENT'], 
            power = row['POWER'], luxury = row['LUXURY'])
            yield dict(row)

    @property
    def filename(self):
        return self._filename

    @filename.setter
    def filename(self, fn):
        self._filename = fn
        self._db = sqlite3.connect(fn)
        self._db.row_factory = sqlite3.Row


class Cars: 
    def __init__(self, **kwargs):
        self.variables = kwargs

    def set_Variable(self, k, v):
        self.variables[k] = v

    def get_Variable(self, k):
        return self.variables.get(k, None)

def main():
    db = Database(filename = 'insurance.sqlite')
    print ('IDENT                       MAKE               MODEL                   
    DISPLACEMENT             POWER              LUXURY')
    for item in db:
        print(item['IDENT'], '            ', item['MAKE'], '            ', 
          item['MODEL'],'            ', item['DISPLACEMENT'],
          '            ', item['POWER'],'            ', item['LUXURY'])


if __name__ == "__main__": main()
4

1 回答 1

2

您不想打印生成器本身,而是想打印生成器返回的每个项目。

for item in db:
    print(item)
于 2013-02-28T17:24:06.743 回答