而不是使用一个新的变量为每一位客户则可以将对象存储在一个Python字典:
d = dict()
for record in result:
objectname = 'Customer' + str(record[0])
customername = str(record[1])
d[objectname] = Customer(customername)
print d
我只是could'nt帮助我的自我书面方式存储在字典对象的示例一些代码(比我想要做的更多)。这就像上瘾。无论如何,我不会使用对象进行这种工作。我可能会使用一个sqlite数据库(可以保存在内存中,如果你想)。但是这段代码告诉你(希望)你如何使用字典来保存客户数据对象:
# Initiate customer dictionary
customers = dict()
class Customer:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
self.address = None
self.zip = None
self.state = None
self.city = None
self.phone = None
def add_address(self, address, zp, state, city):
self.address = address
self.zip = zp
self.state = state
self.city = city
def add_phone(self, number):
self.phone = number
# Observe that these functions are not belonging to the class.
def _print_layout(object):
print object.fname, object.lname
print '==========================='
print 'ADDRESS:'
print object.address
print object.zip
print object.state
print object.city
print '\nPHONE:'
print object.phone
print '\n'
def print_customer(customer_name):
_print_layout(customers[customer_name])
def print_customers():
for customer_name in customers.iterkeys():
_print_layout(customers[customer_name])
if __name__ == '__main__':
# Add some customers to dictionary:
customers['Steve'] = Customer('Steve', 'Jobs')
customers['Niclas'] = Customer('Niclas', 'Nilsson')
# Add some more data
customers['Niclas'].add_address('Some road', '12312', 'WeDon\'tHaveStates', 'Hultsfred')
customers['Steve'].add_phone('123-543 234')
# Search one customer and print him
print 'Here are one customer searched:'
print 'ooooooooooooooooooooooooooooooo'
print_customer('Niclas')
# Print all the customers nicely
print '\n\nHere are all customers'
print 'oooooooooooooooooooooo'
print_customers()
它一直在*尝试*,但它不是必需的。事实上,这是一个非常糟糕的做法。只需使用一个集合。 – delnan 2011-12-30 17:54:49
请更正示例代码中的缩进。你知道,这在Python中很重要。 – 2011-12-30 17:56:48
感谢大家的回复,并感谢我对Python的新手知识。 – user1123221 2011-12-30 18:20:18