我正在尝试创建一个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/