What is class method?

Hrvoje Niksic hniksic at xemacs.org
Mon Aug 25 10:28:40 EDT 2008


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> On Sun, 24 Aug 2008 11:09:46 +0200, Hrvoje Niksic wrote:
>
>> Use [classmethod] when your method needs to know what class it is
>> called from.
>
> Ordinary methods know what class they are called from

I guess I should have added "and no more".  :-)

> Why is this useful? Consider the dict method "fromkeys". You can
> call it from any dictionary, but it doesn't care which dict you call
> it from, only that it is being called from a dict:

That's also a good example of the difference between classmethod and
staticmethod, since fromkeys is smart enough to use the type
information.

>>> class X(dict):
...   pass
...
>>> x = X.fromkeys({1: 2})
>>> type(x)
<class '__main__.X'>     # not <type 'dict'>

If 'fromkeys' were a staticmethod, it would have to be hardcoded to
always create dicts.



More information about the Python-list mailing list