2011-12-30 70 views
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。

我假设我错误地引用了变量,

感谢您的帮助。

+0

的代码看起来不错。向我们显示定义'Customer'的代码 – 2011-12-30 16:50:17

+0

您在什么时候引用objectname对象?如果在循环完成后执行,则自然对象名称将具有在最后一次循环迭代中设置的值。 – exfizik 2011-12-30 16:56:17

+0

添加了客户类,感谢您的快速响应 – user1123221 2011-12-30 16:56:29

回答

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 
相关问题