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