this post was submitted on 27 Jul 2024
27 points (93.5% liked)
Learn Programming
1625 readers
2 users here now
Posting Etiquette
-
Ask the main part of your question in the title. This should be concise but informative.
-
Provide everything up front. Don't make people fish for more details in the comments. Provide background information and examples.
-
Be present for follow up questions. Don't ask for help and run away. Stick around to answer questions and provide more details.
-
Ask about the problem you're trying to solve. Don't focus too much on debugging your exact solution, as you may be going down the wrong path. Include as much information as you can about what you ultimately are trying to achieve. See more on this here: https://xyproblem.info/
Icon base by Delapouite under CC BY 3.0 with modifications to add a gradient
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
len
is a built-in function: https://docs.python.org/3/library/functions.html#lenWhen you do
len("something")
you are passing the stringsomething
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.If you were to try to do
"something".len()
it would try to call the function "len" that exists onstr
. There isn't one.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.At the end of the day,
len(ob)
just defers toob.__len__()
so both are correct, just one's more functional and one's more object oriented.Things prefixed with two underscores are considered private, and typically should not be accessed directly.
https://docs.python.org/3/tutorial/classes.html#private-variables
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:
Both of the above return values are perfectly valid Python.