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

Brent Washburne
  • 12,904
  • 4
  • 60
  • 82

1 Answers1

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 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 ... – Vagelis Dalucas Jun 28 '17 at 14:53