24

I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which doesn't reference a specific instance.

So, what does the first parameter of a @classmethod (canonically 'self') refer to if the method is meant to be called without an instance reference?

Yes - that Jake.
  • 16,725
  • 14
  • 70
  • 96

4 Answers4

38

class itself:

A class method receives the class as implicit first argument, just like an instance method receives the instance.

class C:
    @classmethod
    def f(cls):
        print(cls.__name__, type(cls))

>>> C.f()
C <class 'type'>

and it's cls canonically, btw

Dana
  • 32,083
  • 17
  • 62
  • 73
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
16

The first parameter of a classmethod is named cls by convention and refers to the the class object on which the method it was invoked.

>>> class A(object):
...     @classmethod
...     def m(cls):
...         print cls is A
...         print issubclass(cls, A)

>>> class B(A): pass
>>> a = A()
>>> a.m()
True
True
>>> b = B()
>>> b.m()
False 
True
Torsten Marek
  • 83,780
  • 21
  • 91
  • 98
0

Django does some strange stuff with a class method here:

class BaseFormSet(StrAndUnicode):
    """
    A collection of instances of the same Form class.
    """
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList):
        ...
        self.prefix = prefix or self.get_default_prefix()
        ...

Even though get_default_prefix is declared this way (in the same class):

    @classmethod
    def get_default_prefix(cls):
        return 'form'
boatcoder
  • 17,525
  • 18
  • 114
  • 178
0

The class object gets passed as the first parameter. For example:

class Foo(object):
    @classmethod
    def bar(self):
        return self()

Would return an instance of the Foo class.

EDIT:

Note that the last line would be self() not self. self would return the class itself, while self() returns an instance.

Jason Baker
  • 192,085
  • 135
  • 376
  • 510
  • 6
    This is correct, but it is important to note that `cls` is more commonly used as the first parameter to a classmethod. – Lenna Jan 06 '13 at 20:22