0
我想创建具有变量名称的对象,当我打印出我的objectname变量时,正确的名称被分配给它。但是,当我尝试使用objectname变量创建对象时,创建的对象字面上被称为“objectname”,而不是使用分配给该变量的字符串。我的代码如下:从mysql数据库创建具有变量对象名称的对象
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
因此,所有这将创建一个名为对象名的单个对象,而不是多个对象“Customer1,2,3”等,基于客户数据库表的数量。变量名称基于字符串“Customer”和数据库中的行ID。
我假设我错误地引用了变量,
感谢您的帮助。
的代码看起来不错。向我们显示定义'Customer'的代码 – 2011-12-30 16:50:17
您在什么时候引用objectname对象?如果在循环完成后执行,则自然对象名称将具有在最后一次循环迭代中设置的值。 – exfizik 2011-12-30 16:56:17
添加了客户类,感谢您的快速响应 – user1123221 2011-12-30 16:56:29