What is a "method" in Python?

Question:

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.

Asked By: brilliant

||

Answers:

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.)

Answered By: RichieHindle

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.

Answered By: AndiDog

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 šŸ™‚

Answered By: pepr

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.

Answered By: acmerfight

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.

Answered By: Kevin Markham

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.

Answered By: Malik Singleton

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)
Answered By: Christian Kunert

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.

Answered By: Sergey

The python documentation says 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. …

Answered By: Kai – Kazuya Ito
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.