82

Can anyone, please, explain to me in very simple terms what a "method" is in Python?

The thing is in many Python tutorials for beginners this word is used in such way as if the beginner already knew what a method is in the context of Python. While I am of course familiar with the general meaning of this word, I have no clue what this term means in Python. So, please, explain to me what the "Pythonian" method is all about.

Some very simple example code would be very much appreciated as a picture is worth thousand words.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
brilliant
  • 2,805
  • 11
  • 39
  • 57
  • 1
    "many Python tutorials"? Which specific tutorials are you talking about? We can't recommend a different one if we don't know what you're currently reading. – S.Lott Sep 24 '10 at 12:16
  • 5
    Method is a general term, it has no different meaning in Python, that's probably why it's used so nonchalant. See http://en.wikipedia.org/wiki/Method_(computer_science) – Jochen Ritzel Sep 24 '10 at 12:29
  • @S.Lott: I am sorry, perhaps, I was too absolutistic in passing my judgment regarding Python tutorials. – brilliant Sep 24 '10 at 14:00
  • 1
    I'm not complaining. "many" may be true. But I'm asking a question. Which specific tutorials are you talking about? – S.Lott Sep 24 '10 at 15:03

9 Answers9

92

It's a function which is a member of a class:

class C:
    def my_method(self):
        print("I am a C")

c = C()
c.my_method()  # Prints("I am a C")

Simple as that!

(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • 8
    It's worth noting here that the instance has to be manually passed into the method, and by convention it's passed as `self`. – Skilldrick Sep 24 '10 at 12:10
  • 7
    @Silldrick: You propably mean the right thing, but your comment as-is implies something wrong. The instance doesn't need to be passed explicitly/manually when calling a method on it. But the method has to recieve it explicitly, i.e. you have to manually add a parameter for the instance (which, yes, is called `self` by convention). –  Sep 24 '10 at 12:14
  • 4
    @delnan - Yes, thanks for the clarification - when I say manually passed in what I really mean is it needs to be explicitly received as a parameter, but it's passed in implicitly. – Skilldrick Sep 24 '10 at 12:20
  • 5
    @AaronMcSmooth: AndiDog's answer is certainly more complete. I'd be interested to know whether @brilliant finds it "better", or *too* complete. Sometimes a simple answer is better. (Because I don't like being accused of rep-whoring, I've made my answer CW.) – RichieHindle Sep 24 '10 at 13:52
  • Thank You, RichieHindle, for this answer and for this example. Truth be told, there are some elements in it, which I still need to understand (perhaps, that will be the content of my further questions), but the main thing is clear now: a method is a function - luckily I already know what a function is. Thank You again. – brilliant Sep 24 '10 at 13:53
  • 2
    @brilliant. don't let a simplistic answer confuse you. There is (slightly) more to it than "a method is a function" but the difference is absolutely crucial. Look at the other answer and post new questions for anything that you don't understand about it. – aaronasterling Sep 24 '10 at 13:56
  • 1
    RichieHindle, please don't worry about what AaronMcSmooth said. As I have already stated, Your answer and especially that simple piece of code, helped me a lot, and I really learned from it. I just hope that there are many supporters here who are willing to provide their answers to newbees the way You did. Thanks again! – brilliant Sep 24 '10 at 13:57
  • 1
    @RichieHindle. My initial reaction might have been a little rough and I suppose "rep-whoring" was out of line. It is an insulting answer though. the "that's all there is to it" line is straight up wrong: There's plenty more to it. – aaronasterling Sep 24 '10 at 13:59
  • @AaronMcSmooth: Thaks for saying this. Of course, I will do my further reasearch regarding all those things which I don't understand, but, AaronMcSmooth, I think that fact (that method is a function) I also needed to know, and ,perhaps, I needed to know that in the first place. At the moment I am studying AndiDog's answer. – brilliant Sep 24 '10 at 14:04
  • 1
    @Aaron: How is there more to `It's a function which is a member of a class`? Yes that's not the most basic answer, but it is a 100% complete answer of the question `What is a method` – Falmarri Sep 24 '10 at 17:20
  • 1
    @Falmarri. Try making a class and assigning a function to it as an attribute. Then you have a function which is a member of a class. – aaronasterling Sep 24 '10 at 18:58
  • 1
    @Falmarri. `class Foo: pass`, `def foofunc(): pass`. `f = Foo()`. `f.foofunc()` ?. – aaronasterling Sep 24 '10 at 19:08
  • 1
    I guess you're getting into technicalities now. I wouldn't call that function a member of a class. If you want to be technical, it would be a function being referenced by a class member variable. – Falmarri Sep 24 '10 at 19:10
  • 1
    Just because you can get a function to act like a class member doesn't make it a class member. – Falmarri Sep 24 '10 at 19:11
  • 1
    @Falmarri. What could possibly be meant by a "class member" other than "value referenced by a class level variable"? – aaronasterling Sep 24 '10 at 19:53
  • 1
    Yeah, the member is the reference, not what it's referring to. Take a singleton class for example. If you reference a singleton class to a member variable, you wouldn't call that singleton a class member, that doesn't make any sense. – Falmarri Sep 24 '10 at 20:44
  • 1
    @Falmarri. Well then by that definition, a method cannot possibly be a member of a class because it is itself a value on the same footing as `foo` in my example. So the given definition of method is bunk by that definition of member too. Also, it would make perfect sense to refer to the singleton as a class member. Why can't a value be a member of more than one class? – aaronasterling Sep 24 '10 at 21:01
  • 1
    I think we're arguing technicalities here. – Falmarri Sep 24 '10 at 21:55
  • I think you're trying to use an example that doesn't compile. I posted a question regarding this on http://programmers.stackexchange.com/questions/7212/definition-of-a-method – Falmarri Sep 24 '10 at 22:16
  • 1
    @Falmarri. If course it compiles. it doesn't _run_. It shouldn't run. It makes not sense because even though `fooFunc` is a member of `Foo`, and it's a function, it's not a _method_. – aaronasterling Sep 24 '10 at 22:47
  • 1
    What do you mean it compiles but doesn't run. What you submitted is a syntax error, if I'm interpreting it correct. Are you saying this? http://pastebin.org/1155936 – Falmarri Sep 24 '10 at 22:53
  • 1
    @Falmarri. No I've submitted a correction. The syntax error was because you didn't indent `pass` in `fooFunc`. Either the corrected version or the one that I added (the original) will yield a `TypeError` when you run them. but in both cases `fooFunc` is a function that is a member of `Foo`. – aaronasterling Sep 24 '10 at 22:59
  • 1
    @Falmarri. This is well out of hand for a comments discussion. here's a question: http://stackoverflow.com/questions/3791651/what-constitutes-a-member-of-a-class-what-constitutes-a-method – aaronasterling Sep 24 '10 at 23:11
  • 1
    You can't use non-runnable code as an example for an argument... You can't run this code exactly because you're trying to use a function as a method. – Falmarri Sep 24 '10 at 23:11
46

A method is a function that takes a class instance as its first parameter. Methods are members of classes.

class C:
    def method(self, possibly, other, arguments):
        pass # do something here

As you wanted to know what it specifically means in Python, one can distinguish between bound and unbound methods. In Python, all functions (and as such also methods) are objects which can be passed around and "played with". So the difference between unbound and bound methods is:

1) Bound methods

# Create an instance of C and call method()
instance = C()

print instance.method # prints '<bound method C.method of <__main__.C instance at 0x00FC50F8>>'
instance.method(1, 2, 3) # normal method call

f = instance.method
f(1, 2, 3) # method call without using the variable 'instance' explicitly

Bound methods are methods that belong to instances of a class. In this example, instance.method is bound to the instance called instance. Everytime that bound method is called, the instance is passed as first parameter automagically - which is called self by convention.

2) Unbound methods

print C.method # prints '<unbound method C.method>'
instance = C()
C.method(instance, 1, 2, 3) # this call is the same as...
f = C.method
f(instance, 1, 2, 3) # ..this one...

instance.method(1, 2, 3) # and the same as calling the bound method as you would usually do

When you access C.method (the method inside a class instead of inside an instance), you get an unbound method. If you want to call it, you have to pass the instance as first parameter because the method is not bound to any instance.

Knowing that difference, you can make use of functions/methods as objects, like passing methods around. As an example use case, imagine an API that lets you define a callback function, but you want to provide a method as callback function. No problem, just pass self.myCallbackMethod as the callback and it will automatically be called with the instance as first argument. This wouldn't be possible in static languages like C++ (or only with trickery).

Hope you got the point ;) I think that is all you should know about method basics. You could also read more about the classmethod and staticmethod decorators, but that's another topic.

AndiDog
  • 68,631
  • 21
  • 159
  • 205
  • Super interesting, thanks for the explanation. Seems like an unusually aggressive convention for python (to shift over all subsequent arguments when it is invoked with dot-notation on a class instance), but definitely makes sense. – Luke Davis Jan 09 '17 at 20:58
  • It's not very unusual: [Uniform function call syntax](https://en.wikipedia.org/wiki/Uniform_Function_Call_Syntax) was proposed/implemented in quite a few languages already. – AndiDog Jan 10 '17 at 15:10
27

In Python, a method is a function that is available for a given object because of the object's type.

For example, if you create my_list = [1, 2, 3], the append method can be applied to my_list because it's a Python list: my_list.append(4). All lists have an append method simply because they are lists.

As another example, if you create my_string = 'some lowercase text', the upper method can be applied to my_string simply because it's a Python string: my_string.upper().

Lists don't have an upper method, and strings don't have an append method. Why? Because methods only exist for a particular object if they have been explicitly defined for that type of object, and Python's developers have (so far) decided that those particular methods are not needed for those particular objects.

To call a method, the format is object_name.method_name(), and any arguments to the method are listed within the parentheses. The method implicitly acts on the object being named, and thus some methods don't have any stated arguments since the object itself is the only necessary argument. For example, my_string.upper() doesn't have any listed arguments because the only required argument is the object itself, my_string.

One common point of confusion regards the following:

import math
math.sqrt(81)

Is sqrt a method of the math object? No. This is how you call the sqrt function from the math module. The format being used is module_name.function_name(), instead of object_name.method_name(). In general, the only way to distinguish between the two formats (visually) is to look in the rest of the code and see if the part before the period (math, my_list, my_string) is defined as an object or a module.

Kevin Markham
  • 5,778
  • 1
  • 28
  • 36
4

Sorry, but--in my opinion--RichieHindle is completely right about saying that method...

It's a function which is a member of a class.

Here is the example of a function that becomes the member of the class. Since then it behaves as a method of the class. Let's start with the empty class and the normal function with one argument:

>>> class C:
...     pass
...
>>> def func(self):
...     print 'func called'
...
>>> func('whatever')
func called

Now we add a member to the C class, which is the reference to the function. After that we can create the instance of the class and call its method as if it was defined inside the class:

>>> C.func = func
>>> o = C()
>>> o.func()
func called

We can use also the alternative way of calling the method:

>>> C.func(o)
func called

The o.func even manifests the same way as the class method:

>>> o.func
<bound method C.func of <__main__.C instance at 0x000000000229ACC8>>

And we can try the reversed approach. Let's define a class and steal its method as a function:

>>> class A:
...     def func(self):
...         print 'aaa'
...
>>> a = A()
>>> a.func
<bound method A.func of <__main__.A instance at 0x000000000229AD08>>
>>> a.func()
aaa

So far, it looks the same. Now the function stealing:

>>> afunc = A.func
>>> afunc(a)
aaa    

The truth is that the method does not accept 'whatever' argument:

>>> afunc('whatever')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method func() must be called with A instance as first 
  argument (got str instance instead)

IMHO, this is not the argument against method is a function that is a member of a class.

Later found the Alex Martelli's answer that basically says the same. Sorry if you consider it duplication :)

Community
  • 1
  • 1
pepr
  • 20,112
  • 15
  • 76
  • 139
  • At delnan: You wrote "The instance doesn't need to be passed explicitly/manually when calling a method on it." Actually, you must pass it explicitly. The only syntactic difference is that you do not write it as the first argument inside parentheses. Putting it in front of the method name (separated by dot) and omitting the class identifier is actually a synactic sugar. – pepr Jul 16 '12 at 21:16
0

http://docs.python.org/2/tutorial/classes.html#method-objects

Usually, a method is called right after it is bound:

x.f()

In the MyClass example, this will return the string 'hello world'. However, it is not necessary to call a method right away: x.f is a method object, and can be stored away and called at a later time. For example:

xf = x.f
while True:
    print xf()

will continue to print hello world until the end of time.

What exactly happens when a method is called? You may have noticed that x.f() was called without an argument above, even though the function definition for f() specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used...

Actually, you may have guessed the answer: the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.

If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.

acmerfight
  • 745
  • 1
  • 7
  • 10
0

If you think of an object as being similar to a noun, then a method is similar to a verb. Use a method right after an object (i.e. a string or a list) to apply a method's action to it.

0

To understand methods you must first think in terms of object oriented programming: Let's take a car as a a class. All cars have things in common and things that make them unique, for example all cars have 4 wheels, doors, a steering wheel.... but Your individual car (Lets call it, my_toyota) is red, goes from 0-60 in 5.6s Further the car is currently located at my house, the doors are locked, the trunk is empty... All those are properties of the instance of my_toyota. your_honda might be on the road, trunk full of groceries ...

However there are things you can do with the car. You can drive it, you can open the door, you can load it. Those things you can do with a car are methods of the car, and they change a properties of the specific instance.

as pseudo code you would do:

my_toyota.drive(shop)

to change the location from my home to the shop or

my_toyota.load([milk, butter, bread]

by this the trunk is now loaded with [milk, butter, bread].

As such a method is practically a function that acts as part of the object:

class Car(vehicle)
    n_wheels = 4

    load(self, stuff):
    '''this is a method, to load stuff into the trunk of the car'''
        self.open_trunk
        self.trunk.append(stuff)
        self.close_trunk

the code then would be:

my_toyota = Car(red)
my_shopping = [milk, butter, bread]
my_toyota.load(my_shopping)
0

A method is a function that ‘belongs’ to an object and has a specific name:

    obj.methodname

where obj is some object (this may be an expression), and methodname is the name of a method that is defined by the object’s type.

It is worth of noting: we call method like any other function. More can be found in python tutorial.

Sergey
  • 1
  • 2
0

The python doc explains about a method as shown below:

... A method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. ...

And, the python doc also explains about a function as shown below:

A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body. ...

And, the python doc also explains about an object as shown below:

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer”, code is also represented by objects.)

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is’ operator compares the identity of two objects; the id() function returns an integer representing its identity.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129