3

I am a little confused about functions in Python, and how they are classified. For one, we have functions like print(), that simply encode some instructions and act on input. But also, we have functions like 'str'.capitalize(), that can only act when they have an "executor" attached to them. This might not be a well-informed question, but what are the differences between these forms, and how are they classified?

Wesley
  • 1,217
  • 3
  • 12
  • 16
  • Please read the [Python tutorial](https://docs.python.org/2/tutorial/), as you are asking what a method is. – chepner Aug 28 '15 at 19:41
  • Well that answers my question. Based on that I'm assuming Python is structured like Java. – Wesley Aug 28 '15 at 19:43
  • Some ideas like object oriented programming are similar in different languages. But [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html). – Matthias Aug 28 '15 at 19:56
  • @MilesDavis: one structural difference is Java does not allow functions outside of classes and Python does –  Aug 28 '15 at 19:57

4 Answers4

1

print() is a function in python3 (in python2 it was a statement), and capitalize() is a method.

Please take a look at this answer to clear things up a little bit.

Community
  • 1
  • 1
Igor Pejic
  • 3,658
  • 1
  • 14
  • 32
  • Miles' question has an abstract answer that is the fundamental of the majority of modern programming languages, Object Oriented Programming – mhbashari Aug 29 '15 at 05:44
1

Python is a multi paradigm language that you can write structural and object oriented. Python has built-in functions and built-in classes; for example when you use sequence of characters between two quotation mark (') you instantiate string class.This instance called object. Objects may contain functions or/and other objects. you can access internal functions or object with DOT.

mhbashari
  • 482
  • 3
  • 16
0

print() is a built in function, you can check that like below..

>>> type(print)
<class 'builtin_function_or_method'>
>>> hasattr(print, '__call__')
True

But capitalize() is method of a str class, you can only use this by using string objects.

>>> hasattr('string', 'capitalize')
True
gsb-eng
  • 1,211
  • 1
  • 9
  • 16
0

Python is object oriented. This means we have "objects", which basically enclose their own data, and have their own methods. a String is an example of an object. Another example would be if you have a Person object. You can't just do walk(), you have to do Miles.walk(). You could try walk(Miles). But not everything can walk, so we make the function walk() specific to Person objects.

So yes, Python creators could have made capitalize('str') legal, but they decided to make the capitalize function specific to String objects.

J369
  • 436
  • 7
  • 12
  • `Python is object oriented` isn't exactly true. Python is *object aware* would be a better description. – Josh J Aug 28 '15 at 20:26