好的,所以我正在尝试打印所有汽车对象...我有 2 个问题:
- 我实施的方式
__iter__
可以接受吗? - 我现在得到了我想要的结果,但结果相当丑陋......有没有办法格式化打印以使其看起来更漂亮?
这是我的代码:
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()