【问题标题】:len() function gives an error when i try to use itlen() 函数在我尝试使用时出错
【发布时间】:2019-09-16 17:49:49
【问题描述】:

我正在做一个 codewars 挑战,你必须在字符串上找到最小的线,我决定使用 len() 函数,但每当运行代码时,它都会给我以下错误:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    test.assert_equals(find_short("bitcoin take over the world maybe who knows perhaps"), 3)
  File "/home/codewarrior/solution.py", line 5, in find_short
    if word.len() < l:
AttributeError: 'str' object has no attribute 'len'

这是有缺陷的代码,我真的找不到它有什么问题:

def find_short(s):
    foo = s.split()
    l = 100
    for word in foo:
        if word.len() < l:
            l = word.len()
        else:
            continue

    return l # l: shortest word length

【问题讨论】:

  • AttributeError: 'str' object has no attribute 'len' - 此消息中有什么不清楚的地方?
  • 使用len(word)
  • 在提出问题之前,请确保自己进行一些研究。搜索您提供的错误消息会导致这个已回答的问题:'str' object has no attribute 'len'

标签: python python-3.x


【解决方案1】:

字符串没有len 属性,您可以使用字符串作为参数调用len() 函数。

def find_short(s):
    foo = s.split()
    l = 100
    for word in foo:
        if len(word) < l:
            l = len(word)
        else:
            continue

    return l # l: shortest word length

【讨论】:

    【解决方案2】:

    len 是一个函数,而不是一个方法。

    if len(word) < l:
        l = len(word)
    

    【讨论】:

      【解决方案3】:

      为了完整起见,len确实实际上有一个method counterpart

      word.__len__()
      

      这是 len 独立函数在内部调用的内容。如果您实现一个对象并希望它与len 一起工作,您可以为它实现__len__ 方法。

      除非您有充分的理由,否则不应直接使用它。 len__len__ 调回的数据做一些检查以确保正确性:

      class L:
          def __len__(self):
              return -4
      
      print(len(L()))
      
      ValueError: __len__() should return >= 0
      

      如果您直接使用“dunder 方法”,您将绕过这些检查。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-15
        • 1970-01-01
        • 2021-12-30
        • 2012-02-19
        • 2019-04-05
        相关资源
        最近更新 更多