2015-02-24 78 views
6

我正試圖編寫一個函數,其目的是要通過對象的__dict__並將項目添加到字典中,如果該項目不是函數。 這裏是我的代碼:將項目添加到列表如果它不是函數

def dict_into_list(self): 
    result = {} 
    for each_key,each_item in self.__dict__.items(): 
     if inspect.isfunction(each_key): 
      continue 
     else: 
      result[each_key] = each_item 
    return result 

如果我沒有記錯,inspect.isfunction應該認識到lambda表達式的功能,以及,是否正確?但是,如果我寫

c = some_object(3) 
c.whatever = lambda x : x*3 

那麼我的功能仍然包括lambda。有人可以解釋爲什麼這是嗎?

舉例來說,如果我有這樣一個類:

class WhateverObject: 
    def __init__(self,value): 
     self._value = value 
    def blahblah(self): 
     print('hello') 
a = WhateverObject(5) 

所以,如果我說print(a.__dict__),應該還給{_value:5}

+0

你能展示一個自包含的例子來證明問題嗎? – BrenBarn 2015-02-24 06:17:50

+0

@Tyler函數意味着,你期望什麼?你的情況不起作用? – Nilesh 2015-02-24 06:18:37

回答

4

你實際上是檢查是否each_key是一個函數,其中最有可能不是。實際上,你必須檢查的價值,這樣

if inspect.isfunction(each_item): 

可以證實這一點,通過包括print,這樣

def dict_into_list(self): 
    result = {} 
    for each_key, each_item in self.__dict__.items(): 
     print(type(each_key), type(each_item)) 
     if inspect.isfunction(each_item) == False: 
      result[each_key] = each_item 
    return result 

此外,您還可以使用字典解析編寫代碼,這樣

def dict_into_list(self): 
    return {key: value for key, value in self.__dict__.items() 
      if not inspect.isfunction(value)} 
+0

是的,你的功能是正確的。然而,你怎麼知道每個關鍵很可能不是一個函數? – Tyler 2015-02-24 06:49:51

+0

@Tyler'__dict__'將有字符串鍵,值是相應的對象。 – thefourtheye 2015-02-24 06:51:25

0

我能想到的一個簡單的方法來找到對象通過目錄和變量蟒蛇代替inspect模塊的調用方法。

{var:self.var for var in dir(self) if not callable(getattr(self, var))} 

請注意,這確實是假設你沒有overrided類的__getattr__方法做的比得到的屬性以外的東西。