如果项目不是函数,则将项目添加到列表中

时间:2015-02-24 06:15:56

标签: python python-3.x dictionary inspect

我正在尝试立即编写一个函数,其目的是遍历一个对象的__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应该将lambdas识别为函数,对吗?但是,如果我写

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}

2 个答案:

答案 0 :(得分: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)}

答案 1 :(得分:0)

我可以想到一种通过python的dir和callable方法而不是inspect模块来查找对象变量的简单方法。

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

请注意,这确实假设您没有覆盖类的__getattr__方法来执行除获取属性之外的其他操作。