1

Some list operations are reached by a dot notation

C.append(e)

while other operations requires the list object as an argument to a function, as in

len(C)

Why this happens? Are there any rules whether functionality regarding an object is reached through the first way (method) or the second one (function)? Thanks.

asked Feb 21, 2017 at 12:48
4
  • Because you need a list to append, append is an instance method because you need an instance for it to work, but to find length you only need to pass an argument. len is a global builtin. Commented Feb 21, 2017 at 12:50
  • usually ones with brackets return a value Commented Feb 21, 2017 at 12:51
  • In the case of len, I believe it just calls the object's __len__ method anyway. When in doubt, consult the documentation. Commented Feb 21, 2017 at 12:51
  • 2
    Related: The advantages of having static function like len(), max(), and min() over inherited method calls. Commented Feb 21, 2017 at 12:52

1 Answer 1

1

There is no difference for many built-in functions. The global functions like len, iter, str are calls to object methods __len__, __iter__, __str__ etc.

See Basic customization and Emulating container types in Python reference:

object.__len__(self)

Called to implement the built-in function len(). Should return the length of the object, an integer>= 0. ...

Advantage of such soluttion is that an object can override these special functions just by overriding corresponding "double-underscore" methods, e.g __len__.

Although append does not have a built-in, since it is a less universal operation than len, str etc.

answered Feb 21, 2017 at 12:53
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.