hasattr判断是不是可迭代类型的方法

实验一、

print(hasattr(1,"len"))
print(hasattr(list,"len"))
print(hasattr("dddd","len"))
print(hasattr(dict(a=1,b=2),"len"))
print(hasattr(set(),"len"))
False
False
False
False
False

实验二、
class Coordinate:
    x = 10
    y = -5
    z = 0
 
point1 = Coordinate() 
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no'))  # 没有该属性


实验三、
print(hasattr(1,"__len__"))
print(hasattr(list,"__len__"))
print(hasattr("dddd","__len__"))
print(hasattr(dict(a=1,b=2),"__len__"))
print(hasattr(set(),"__len__"))

False
True
True
True
True

建议:if hasattr(N, '__len__') and (not isinstance(N, str))

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果一个对象是可迭代对象,那么它必须实现了迭代器协议,即实现了 `__iter__()` 方法,返回一个迭代器对象。我们可以通过内置函数 `iter()` 来判断一个对象是否是可迭代对象,如果可以使用 `iter()` 函数将其转换成迭代器对象,则说明它是可迭代对象,否则不是可迭代对象。下面演示了如何使用 `iter()` 函数来判断一个对象是否是可迭代对象: ```python lst = [1, 2, 3] dct = {'a': 1, 'b': 2} s = 'hello' n = 123 print(f"lst is iterable: {hasattr(lst, '__iter__')}") # 输出:lst is iterable: True print(f"dct is iterable: {hasattr(dct, '__iter__')}") # 输出:dct is iterable: True print(f"s is iterable: {hasattr(s, '__iter__')}") # 输出:s is iterable: True print(f"n is iterable: {hasattr(n, '__iter__')}") # 输出:n is iterable: False # 使用 iter() 函数检查对象是否是可迭代对象 print(f"lst is iterable: {iter(lst) is not None}") # 输出:lst is iterable: True print(f"dct is iterable: {iter(dct) is not None}") # 输出:dct is iterable: True print(f"s is iterable: {iter(s) is not None}") # 输出:s is iterable: True print(f"n is iterable: {iter(n) is not None}") # 输出:n is iterable: False ``` 在上述例子中,我们分别使用 `hasattr()` 函数和 `iter()` 函数来判断不同类型的对象是否是可迭代对象。需要注意的是,虽然字符串、列表、元组、集合、字典等容器类型都是可迭代对象,但是数字和布尔类型不是可迭代对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值