我理解类是一种将属性和方法捆绑在一个对象中的结构。然而,我认为我从未真正掌握它们的全部功能。我通过使用“字典嵌套字典”数据结构来自学处理大量数据。现在我在考虑,如果我想与世界其他人一样,那么我需要在我的代码中实现类,但我不知道如何进行过渡。
我有一个脚本,从SQL查询中获取销售订单信息,对数据执行操作,并将其输出到CSV文件。
1) (目前的做法是将所有订单存储在字典嵌套字典中)
我有一个脚本,从SQL查询中获取销售订单信息,对数据执行操作,并将其输出到CSV文件。
1) (目前的做法是将所有订单存储在字典嵌套字典中)
cursor.execute(querystring)
# create empty dictionary to hold orders
orders = {}
# define list of columns returned by query
columns = [col[0] for col in cursor.description]
for row in cursor:
# create dictionary of dictionaries where key is order_id
# this allows easy access of attributes given the order_id
orders[row.order_id] = {}
for i, v in enumerate(columns):
# add each field to each order
orders[row.order_id][v] = row[i]
# example operation
for order, fields in orders.iteritems():
fields['long'], fields['lat'] = getLongLat(fields['post_code'])
# example of another operation
cancelled_orders = getCancelledOrders()
for order_id in cancelled_orders:
orders[order_id]['status'] = 'cancelled'
# Other similar operations go here...
# write to file here...
2) (如果我使用类)我认为我会这样做:
class salesOrder():
def __init__(self, cursor_row):
for i, v in enumerate(columns):
setattr(self, v, cursor_row[i])
def getLongLat(self, long_lat_dict):
self.long, self.lat = long_lat_dict[self.post_code]['long'], long_lat_dict[self.post_code]['lat']
def cancelOrder(self):
self.status = 'cancelled'
# more methods here
cursor.execute(querystring)
# create empty dictionary to hold orders
orders = {}
# define list of columns returned by query
columns = [col[0] for col in cursor.description]
for row in cursor:
orders[row.order_id] = salesOrder(row)
orders[row.order_id].getLongLat()
# example of another operation
cancelled_orders = getCancelledOrders()
for order_id in cancelled_orders:
orders[order_id].cancelOrder()
# other similar operations go here
# write to file here
我只是感觉我还没有完全理解如何最好地使用类。我是否对如何使用类有了完全错误的想法?我所做的是否有道理,但需要重构?或者我试图用类来达到错误的目的?
row
似乎是一个类对象(例如row.order_id
)。 (b)row.column
不起作用。 (c) 让我们回到一点,我认为你将数据放入字典的原因是为了方便查找和更新。然而,这就是你的数据库所用的,为什么不直接查询数据库并进行更新呢? - Hai Vu