gpt4 book ai didi

python - 检查 Python 模块中是否存在类型

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:52 24 4
gpt4 key购买 nike

确定对象类型是否包含在特定模块中的最 Pythonic 方法是什么?

例如,假设我想匹配日期时间模块中的日期、时间和日期时间类。

import datetime
mylist = [obj1, obj2, obj3, ...]
for obj in mylist:
if type(obj) in [datetime.datetime, datetime.time, datetime.date]:
#Do thing

为每个循环创建三者的匹配实例似乎很愚蠢。有没有更简单的方式来表达“if type(obj) in some-module”?

最佳答案

isinstance()可以检查多种类型:

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

if isinstance(obj, (datetime.datetime, datetime.time, datetime.date)):

关于python - 检查 Python 模块中是否存在类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com