0

so there is a string, lets say a='abc' and two built in string methods for that string object (and string class in general):

len(a)
a.capitalize()

So when is first syntax, method(object), used over the second, object.method() ?

Thanks a lot

2
  • len is not a string method. It is a built-in function. Commented Jun 27, 2017 at 22:14
  • The documentation will tell which is the right syntax. Commented Jun 27, 2017 at 22:26

1 Answer 1

3

The first function is a built-in function that is not associated with any class. You can view a list of all builtins available to you using dir(__builtins__):

>>> dir(__builtins__)
'ArithmeticError', 'AssertionError', ...  'len', ... 'vars', 'zip']

len() is designed to return the size of any iterable, not just a string.

The second function is actually a method of the builtin class str. You can peruse the methods of str with dir(str), and confirm capitalize is an instance method of str.

>>> 'capitalize' in dir(str)
True

Instance methods are invoked on the instances of the object, such as 'abc'.capitalize(). This means that the call passes abc as an invisible argument to capitalize. Methods are meant to work only on instances of that class type.

Sign up to request clarification or add additional context in comments.

1 Comment

I thank you all for your replies, I am new in Python and was I studying from here (tutorialspoint.com/python/python_strings.htm) were len() is registered as a built-in string method ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.