Just started as in, I’m about an hour into a 4 hour intro video. Seeing two basic ways of manipulating things and don’t understand the difference.

If I want to know the length of a string and I just guess at how to do it I would try one of these two things,

  1. Len(string)
  2. string.len()

What is the difference between these types of statements? How do I think about this to know which one I should expect to work?

  • jjjalljs
    link
    fedilink
    arrow-up
    15
    ·
    2 个月前

    len is a built-in function: https://docs.python.org/3/library/functions.html#len

    When you do len("something") you are passing the string something to it, and it returns how long it is. You can pass it other things like lists or sets, and it will tell you how many things are in them, too.

    >>> len
    <built-in function len>
    >>> len("something")
    9
    
    >>> len([1,2,3,4])
    4
    >>> len({"a", "b", "c"})
    3
    

    If you were to try to do "something".len() it would try to call the function “len” that exists on str. There isn’t one.

    >>> "something".len()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'str' object has no attribute 'len'
    

    https://docs.python.org/3/library/stdtypes.html#textseq

    Scroll down a little to “String Methods” and you can see what methods are available on strings.

    This is kind of language specific. Now you know that when you want to know how long something is in Python, you generally use the built-in len. If you’re dealing with some other type of object, you’d check what methods it provides and what it inherits from. There’s a lot of documentation reading in software development. A good IDE also helps.

    • charolastra@programming.dev
      link
      fedilink
      arrow-up
      3
      ·
      edit-2
      2 个月前

      At the end of the day, len(ob) just defers to ob.__len__() so both are correct, just one’s more functional and one’s more object oriented.

        • charolastra@programming.dev
          link
          fedilink
          arrow-up
          3
          ·
          edit-2
          2 个月前

          Keyword “typically”. If I’m overriding dunder methods, then I’ll typically need to call the super method as well. It’s not like it’s forbidden.

          Consider the following:

          class MyStr(str):
               def len(self):
                    return len(self)
                    # OR
                    return self.__len__()
          

          Both of the above return values are perfectly valid Python.