変数名を持つオブジェクトを作成しようとしていますが、オブジェクト名変数を出力する際に正しい名前が割り当てられています。しかし、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に基づいています。
私はあなたの助けのための
おかげで、私は間違って変数を参照していますと仮定します。
そのコードがよさそうだ:彼らは辞書にいる一度
しかし、彼らはいつでも必要に応じて繰り返し処理することができます。 'Customer'が定義されているコードを表示してください –
どの時点でobjectnameオブジェクトを参照していますか?ループが終了した後に行うと、自然にオブジェクト名は最後のループ反復で設定された値になります。 – exfizik
クイックレスポンスのためにカスタマークラスを追加しました – user1123221