2015-02-24 34 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__方法做的比得到的属性以外的东西。