Skip to main content
ertius.org

Python Method Types

Decorators

One thing to remember is that:

class SomeClass(object):
    @decorator
    def something(self):
        print "Did something"

is the same as:

class SomeClass(object):
    def something(self):
        print "Did something"

    something = decorator(something)

The first version is just a bit easier to read.

Instance methods

These are the regular methods you see all the time in Python code:

class SomeClass(object):
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print "Hello", self.name

Here, both __init__ and say_hello are /instance/ methods. By convention, an instance method’s first argument is called self, but Python does not enforce this. Anyone else who looks at your code, will, though.

Class methods

class SomeClass(object):
    @classmethod
    def say_hello(cls, name):
        print "Hello", name

Static methods

class SomeClass(object):
    @staticmethod
    def say_hello(name):
        print "Hello", name

Because the say_hello method is decorated with staticmethod, it is made into a static method, that doesn't take self as an argument and is just hanging off the class namespace.