我正在尝试创建具有变量名称的对象,当我打印出我的objectname变量时,会为其分配正确的名称。但是当我尝试使用objectname变量创建一个对象时,创建的对象字面上称为“objectname”,而不是使用分配给变量的字符串。我的代码如下:
class Customer:
# Initiliaise method, creating a customer object
def __init__(self,name):
self.name = name
print "Customer %s Added" % (self.name)
# Print out details
def output(self):
print "This is the customer object called %s" % (self.name)
## Create the Customer objects, from the Customer table
# Pull the Customers out of the Customer table
# SQL
cursor.execute("SELECT * FROM Customer")
result = cursor.fetchall()
for record in result:
objectname = 'Customer' + str(record[0])
print objectname # This prints "Customer1..2" etc
# customername is the exact name as in the database
customername = str(record[1])
# Use the above variables pulled from the database to create a customer object
objectname=Customer(customername)
# We need to count the number of customer objects we create
customercount = customercount + 1
因此,根据Customer DB表中的数字,所有创建的对象都是一个名为objectname的对象,与多个对象“Customer1,2,3”等相对。变量名称基于字符串“Customer”和数据库中的行ID。
我假设我错误地引用了变量,
感谢您的帮助。
答案 0 :(得分:1)
应将每个objectname
添加到命名空间中,以便以后可以轻松访问它们引用的对象。
最简单的方法是使用字典:
customers = {}
for record in result:
objectname = 'Customer' + str(record[0])
customers[objectname] = Customer(str(record[1]))
customercount = len(customers)
...
customers['Customer1'].output()
事实上,通过使用客户ID本身作为字典键,您可以使事情变得更简单:
customers = {}
for record in result:
customers[record[0]] = Customer(str(record[1]))
customercount = len(customers)
...
customers[1].output()
请注意,如果所有客户对象都有一个单独的objectname
变量,那么将它们作为一个组进行处理会更加困难。
但是一旦他们进入字典,他们可以在必要时进行迭代:
for identifier, customer in customers.iteritems():
print 'Customer%d:' % identifier, customer.name