从MySQL数据库创建具有可变名称的对象

0 投票
1 回答
1735 浏览
提问于 2025-04-17 09:16

我正在尝试创建一些名字可以变化的对象。当我打印出我的对象名变量时,确实得到了正确的名字。但是,当我用这个对象名变量去创建对象时,创建出来的对象名字却是“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

所以这样做只会创建一个叫做objectname的对象,而不是根据客户数据库表中的数字创建多个对象,比如“Customer1、Customer2、Customer3”等等。这个变量名是基于字符串“Customer”和数据库中的行ID。

我想我可能是错误地引用了这个变量。

谢谢你的帮助。

1 个回答

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

撰写回答