Date: February 21st 2016
Last updated: February 21st 2016
A class method is similar (on the surface) to a staticmethod. You can use a class method on a call to the class or an instance of a class. This method is not bound to an instance, but is bound to the class. The first parameter of a classmethod is normally cls. To create a classmethod use the built-in decorator function.
Example from here:
class Foo(object): def hello(cls): print("hello from %s" % cls.__name__) Foo.hello() #"Hello from Foo"
class Base(object): """ silly example that is better suited as a normal method """ rand_string = '12 23 this is a test 34 2' def get_num(cls): """return a list of numbers from a string""" # note the use of cls to call rand_string attached to the class res = [int(s) for s in cls.rand_string.split() if s.isdigit()] return res
In this example, rand_string is a permanent fixture of class Base. There is no 'unbound' version of this classmethod.
# calling from class Base #<class 'classmethods.Base'> Base.rand_string #'12 23 this is a test 34 2' Base.get_num #<bound method type.get_num of <class 'classmethods.Base'>> Base.get_num() #[12, 23, 34, 2] # Calling from an instantiated variable b = Base() b.get_num() #[12, 23, 34, 2]
classmethods can be inherited:
class Dev(Base): pass Dev.get_num() #[12, 23, 34, 2]
classmethods cannot access instance variables of an object:
class Base(object): """same class as above; now with init function defined""" ... def __init__(self, name): self.name = name def get_num(cls): ... print self.name Base.get_num() #NameError: global name 'self' is not defined
- ... A variant of the static method is the class method. Instead of receiving the instance as the first parameter, it is passed the class. It, too, is defined using a decorator: See this tutorial.
- ... doesn't require an instance. Instead, the class will automatically be sent as the first argument. A class method is declared with the @classmethod decorator. See this forum thread
- ... Class methods are methods that are not bound to an object, but to… a class! See this tutorial
- ... or when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. See this forum thread
- ... have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all. See this forum thread.
- ... means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance. See this forum thread.