2011-08-03 275 views
0

我有一個大的字典。我想將每個鍵值對分配給一個類的屬性。目前我在下面的代碼段中有一些內容。它的作品,但它不漂亮。有一個更好的方法嗎?從字典中分配屬性值

僞蟒蛇片段:

config = A large dictionary 

self.Width = config['width'] 
self.Height = config['height'] 
self.Text = config['text'] 
self.Font = config['font'] 
etc... 

回答

5

很簡單:

for key, value in config.iteritems(): 
    # Customize key here, for example transform 'text_height' to 'TextHeight' or 
    # use 'key.title()' to obtain titlecased keys... 
    setattr(self, key, value) 

你可能想要做key.title(),但實例屬性建議是在python全部小寫。

+1

使用'key.title()'轉換「寬度」鍵「寬」屬性。 – PaulMcG

+0

@Paul:你快了;) – GaretJax

+0

考慮多字鍵的情況可能會很好。例如,應將'config ['text_height']'分配給'self.TextHeight'? –

2

,如果你不關心的首字母大寫,你可以只是做:

self.__dict__.update(config) 
+0

如果類定義了「@屬性」或定製了「__setattr__」方法,則不起作用。 – GaretJax

+0

@GaretJax:我承認 - 這有點破解。 ...只是把它扔到那裏,看看我是否會發火焰:)這兩種情況似乎並沒有太大的限制(可能還有一些隱藏的警告) – Gerrat

+0

是的,就像老式的課程...;) – GaretJax