Python 从mysql数据库创建具有可变对象名称的对象
我试图创建具有变量名的对象,当我打印出objectname变量时,会为其指定正确的名称。但是,当我尝试使用objectname变量创建对象时,创建的对象字面上称为“objectname”,而不是使用分配给变量的字符串。我的代码如下:Python 从mysql数据库创建具有可变对象名称的对象,python,Python,我试图创建具有变量名的对象,当我打印出objectname变量时,会为其指定正确的名称。但是,当我尝试使用objectname变量创建对象时,创建的对象字面上称为“objectname”,而不是使用分配给变量的字符串。我的代码如下: class Customer: # Initiliaise method, creating a customer object def __init__(self,name): self.name = name print "Customer %s
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的单一对象,而不是基于Customer DB表中的数字创建多个对象“Customer1、2、3”等。变量名基于字符串“Customer”和数据库中的行ID
我假设我引用的变量不正确
感谢您的帮助。应将每个
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
代码看起来不错。向我们展示定义了
Customer
的代码在什么位置引用objectname对象?如果在循环完成后执行此操作,对象名称自然会在上一次循环迭代中设置值。添加了customer类,感谢您的快速响应我尝试在循环后及其内部引用创建的对象,但在打印objectname变量的地方,我得到了正确的输出“Customer1”和“Customer2”,但是该对象被称为“objectname”,而不是变量objectname中的“Customer1”。我可以使用objectname.output(),但不能使用Customer1.output()。我希望这更有意义。