2015-05-08 61 views
4

我想從字典中創建類比實例具有多於類的屬性。我已經從這個鏈接閱讀同一個問題的答案:Creating class instance properties from a dictionary?。問題是,我不能在類定義中編寫__init__,因爲我使用SQLAlchemy聲明式樣式類定義。另外type('className', (object,), dict)會創建不需要的錯誤屬性。 這裏是我找到了解決辦法:從字典創建類實例?

dict = {'key1': 'value1', 'key2': 'value2'} 
object = MyClass(**dict) 

但如果dict有多餘的按鍵不起作用:

dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'} 
object = MyClass(**dict) # here need to ignore redundant_key 

是否有除了直接刪除任何解決方案,所有多餘的按鍵從dict

+1

什麼是'redundant_key'? – RafaelC

+0

你想如何爲'MyClass'寫'__init__'?對不起,我不熟悉SQLAlchemy聲明式樣式類的定義。 –

+0

@RafaelCardoso redundant_key是存在於字典中的一個關鍵字,但不存在於類屬性中。 – Demyanov

回答

6

使用classmethod過濾字典,並返回該對象。

然後你不必強迫你的__init__方法接受字典。

import itertools 

class MyClass(object): 
    @classmethod 
    def fromdict(cls, d): 
     allowed = ('key1', 'key2') 
     df = {k : v for k, v in d.iteritems() if k in allowed} 
     return cls(**df) 

    def __init__(self, key1, key2): 
     self.key1 = key1 
     self.key2 = key2 

dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'} 

ob = MyClass.fromdict(dict) 

print ob.key1 
print ob.key2 
1

另一解決方案是Filter dict to contain only certain keys

dict_you_want = { your_key: dict[your_key] for your_key in your_keys } 
+0

然後在__init__函數中添加一行,如:'self .__ dict __。update(dict_you_want)' –