2011-12-30 6 views
0

変数名を持つオブジェクトを作成しようとしていますが、オブジェクト名変数を出力する際に​​正しい名前が割り当てられています。しかし、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 

ので、作成することすべてが顧客DBテーブルの数に基づいて、など複数のオブジェクトではなく、「Customer1,2,3」のObjectNameと呼ばれる単一のオブジェクトです。変数名は、文字列 "Customer"とデータベースの行IDに基づいています。

私はあなたの助けのための

おかげで、私は間違って変数を参照していますと仮定します。

+0

そのコードがよさそうだ:彼らは辞書にいる一度

しかし、彼らはいつでも必要に応じて繰り返し処理することができます。 'Customer'が定義されているコードを表示してください –

+0

どの時点でobjectnameオブジェクトを参照していますか?ループが終了した後に行うと、自然にオブジェクト名は最後のループ反復で設定された値になります。 – exfizik

+0

クイックレスポンスのためにカスタマークラスを追加しました – user1123221

答えて

1

objectnameは、参照先のオブジェクトに後から簡単にアクセスできるように名前空間に追加する必要があります。

customers = {} 
for record in result: 
    customers[record[0]] = Customer(str(record[1])) 
customercount = len(customers) 
... 
customers[1].output() 

を:辞書のキーとして顧客IDそのものを使用することにより

customers = {} 
for record in result: 
    objectname = 'Customer' + str(record[0]) 
    customers[objectname] = Customer(str(record[1])) 
customercount = len(customers) 
... 
customers['Customer1'].output() 

は、実際には、あなたは物事がもっと簡単にすることができます:

これを実行する最も簡単な方法は、辞書を使用することですすべての顧客オブジェクトに個別のobjectname変数がある場合は、それらをグループとして処理する方がはるかに難しいことに注意してください。

for identifier, customer in customers.iteritems(): 
    print 'Customer%d:' % identifier, customer.name 
関連する問題