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

Tyl*_*ler 6 python dictionary inspect python-3.x

我正在尝试立即编写一个函数,其目的是遍历一个对象__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
Run Code Online (Sandbox Code Playgroud)

如果我没弄错的话,inspect.isfunction应该将lambdas识别为函数,对吗?但是,如果我写的话

c = some_object(3)
c.whatever = lambda x : x*3
Run Code Online (Sandbox Code Playgroud)

然后我的功能仍然包括lambda.有人可以解释为什么会这样吗?

例如,如果我有这样的类:

class WhateverObject:
    def __init__(self,value):
        self._value = value
    def blahblah(self):
        print('hello')
a = WhateverObject(5)
Run Code Online (Sandbox Code Playgroud)

所以,如果我说print(a.__dict__),它应该回馈{_value:5}

the*_*eye 4

您实际上正在检查是否each_key是一个函数,而很可能不是。您实际上必须检查该值,如下所示

if inspect.isfunction(each_item):
Run Code Online (Sandbox Code Playgroud)

您可以通过包含 来确认这一点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
Run Code Online (Sandbox Code Playgroud)

另外,您可以使用字典理解编写代码,如下所示

def dict_into_list(self):
    return {key: value for key, value in self.__dict__.items()
            if not inspect.isfunction(value)}
Run Code Online (Sandbox Code Playgroud)