user11074017
user11074017

Reputation:

is len() a function or method in python?

In the context of object oriented programming, a function is different from a method.

when i examine the help doc, this piece of code

?len

outputs

Signature: len(obj, /)
Docstring: Return the number of items in a container.
Type:      builtin_function_or_method

does this imply that len() could be function or method depends on concrete situation?

Upvotes: 0

Views: 317

Answers (2)

deceze
deceze

Reputation: 522501

There's one builtin len function. You use it like len(obj). Each object can implements its own __len__ method to override what len() will return; len the function invokes __len__ the method.

If any object chooses to also implement a len method, it may do that, but that has nothing to do with the len function or __len__ convention.

builtin_function_or_method just means that the manual doesn't specifically distinguish between these two things and lumps them all into the same type.

Upvotes: 3

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

len() Is a function, while there is __len__() that is method.

read Here for more information.

Upvotes: 2

Related Questions