是否可以在循環中生成變量名稱?在循環中生成變量名稱
的簡單情況:
class product():
self.shop1_name = None
self.shop1_price = None
self.shop2_name = None
self.shop2_price = None
...
p = product()
# shops is a list of shops
for i, shop in enumerate(shops[0:5]):
p.shop+i+1_name = shop.name # so shop1_name in first loop, shop2_name in second etc...
p.shop+i+1_price = shop.price
所以有很多屬性shop1_price, shop2_price...shop10_price
,我想填補他們在一個循環中不要用手有寫所有這些。
可能嗎?
'shop.name'不會像Javascript那樣工作。 'shop ['name']'然而。 – mgilson