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

Adding items to a list if it's not a function

我现在正在尝试编写一个函数,其目的是遍历一个对象的 __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:

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

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

您实际上是在检查 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)}

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

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

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