2015-10-25 113 views
4

我已經經歷了這些問題了,Python的初始化多個變量相同的初始值

  1. Python assigning multiple variables to same value? list behavior
    關注的元組,我只想變量可以是字符串,整數或字典
  2. More elegant way of declaring multiple variables at the same time
    的問題有一些我想問一下,但接受的答案是非常複雜

所以我想要實現的,

我宣佈這個變量,我想減少這種聲明來爲代碼儘可能少線。

details = None 
product_base = None 
product_identity = None 
category_string = None 
store_id = None 
image_hash = None 
image_link_mask = None 
results = None 
abort = False 
data = {} 

什麼是最簡單,易於維護?

+0

你會使用字典。 – vaultah

+0

多數民衆贊成在複雜的,我不得不調用'dicitonary ['細節']和'KeyErrors'吸,加ide不會突出無效的密鑰,但變量。如果我必須使用'details = dicitonary ['details']',那麼最好使用'details = None',而不是這一輪創建,查找和KeyErrors。 – Rivadiz

+0

你如何定義複雜? – CrakC

回答

9

我同意其他答案,但想解釋的重要一點在這裏。

對象是單例對象。將None對象分配給變量多少次,使用同一個對象。所以

x = None 
y = None 

等於

x = y = None 

,但你不應該做同樣的事情在Python任何其他對象。例如,

x = {} # each time a dict object is created 
y = {} 

不等於

x = y = {} # same dict object assigned to x ,y. We should not do this. 
3

details, producy_base, product_identity, category_string, store_id, image_hash, image_link_mask, results = None, None, None, None, None, None, None, None; abort = False; data = {}

就是這樣。

13

首先,我會建議你不要這樣做。這是不可讀的,非Pythonic。然而,你可以減少類似的行數:

details, product_base, product_identity, category_string, store_id, image_hash, image_link_mask, results = [None] * 8 
abort = False 
data = {}