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?

  • Gyroplast@pawb.social
    link
    fedilink
    arrow-up
    4
    ·
    4 months ago

    What is the difference between these types of statements?

    Technically, len() is a Python built-in function, while "some string".len() would be an instance method of a string object, if such an instance method existed.

    How do I think about this to know which one I should expect to work?

    As a very general rule of thumb, I would recommend to keep the list of built-in functions close and memorize the “popular ones” over time. These are special. Anything else you encounter usually is an instance or class method, or a plain function without any object-oriented shenanigans, depending on how structured the code is you are looking at.

    Learn to navigate the Python reference docs. Use the search function liberally if you don’t come from a search engine result, anyway, or jump directly to the docs for the module you’re interested in to see what functionality it offers, and how to use it.

    Python is annoyingly flexible, and does not strictly enforce a single way to do anything, so learning what to expect always ends up as building an intuition, and actively looking up documentation for the modules, classes, or functions you intend to use until you have encountered enough (good) Python code to have reasonable expectations in the first place.

    TL;DR: grep the relevant module’s docs, or Python built-ins. It’s typically one or the other where you find detailed help.