python - 生成可以不带参数调用的 python 内置对象列表

标签 python

我正在尝试创建一个Python内置类型对象列表,如[{},(),[],'',0.....],可以在没有参数的情况下调用

我不知道如何写理解。我有以下代码

[getattr(___builtins___,x)() for x in dir(___builtins___)]

某些元素不可调用,有些元素需要参数,因此上述内容不起作用

最佳答案

正如 g.d.d.c 在评论中暗示的那样,这可能是 X-Y problem 。但如果您只是为了好玩而这样做,请不要使用列表理解。编写一个处理异常的生成器:

def no_arg_builtins():
  for builtin in dir(__builtins__):
    o = getattr(__builtins__, builtin)
    if callable(o):
      try:
        yield o()
      except TypeError:
        pass # Called incorrectly
    else:
      pass # not callable

或者,如果您只想要内置类型的列表,请考虑使用 types module ,或过滤内置函数为“type”类型的情况:

(t for t in dir(__builtins__) if type(getattr(__builtins__, t)) == type([].__class__))

最后,您可以使用inspect.getargspec确定有关可调用数量的具体信息。

关于python - 生成可以不带参数调用的 python 内置对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25756763/

相关文章:

python - Django - importError 在/博客。 (没有名为 urls 的模块)

Python 3.7 递归删除动态 JSON 字典/列表中不在列表中的名称的项目

python - is 运算符和 == 运算符

python - 使用 Python 中的 Pandas,为每个组选择最高值的行

python - 列表到Python中的字典转换

python - 合并两个不同的数据框

python - 拆分方法如何工作?

python - pd.to_datetime 未将 datetime 转换为 int 以进行 df.rolling 计算

python - scipy.ndimage.imread 和 matplotlib.pyplot.imread 有什么区别?

python - 如何用Python/Pandas减去2列未对齐的数据?