Welcome, guest | Sign In | My Account | Store | Cart

Class methods that do not require an object instance.

Python, 7 lines
1
2
3
4
5
6
7
>>> class Class:
... 	class StaticFudge:
... 		def __call__(self): print "I do not require an instance."
... 	classmethod = StaticFudge()
... 
>>> Class.classmethod()
I do not require an instance.

2 comments

rbeer 20 years, 3 months ago  # | flag

Where is the discussion? Very nice approach! Please do not omit the discussion. If this is supposed to help people with intermediate python knowledge you should be more specific about when and why the problem you're trying to solve occurs and what's your paricular trick for solving the problem?

Toon Verstraelen 17 years, 5 months ago  # | flag

static methods and classmethods in python 2.2 and later. Python 2.2 and later support static methods by using the built in staticmethod function. It looks like an ugly hack, but it works.

From the python documentation:


class C:
    def f(arg1, arg2, ...): ...
    f = staticmethod(f)

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.


In addition to static methods, python also has classmethods:

From the python documentation:


class C:
    def f(cls, arg1, arg2, ...): ...
    f = classmethod(f)

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.


Created by Clark Evans on Sat, 24 Mar 2001 (PSF)
Python recipes (4591)
Clark Evans's recipes (1)
Python Cookbook Edition 1 (103)

Required Modules

  • (none specified)

Other Information and Tasks