2011-12-30 69 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 
相關問題