[Tutor] Staticmethod & Classmethod Question
Steven D'Aprano
steve at pearwood.info
Sun Feb 26 03:37:14 CET 2012
Chris Kavanagh wrote:
> I know this will sound stupid, but why would the method care which
> instance it's called on?? I think this is where my confusion is coming
> in. . .I hope I've made sense here. . .
Typical use for class instances is to store per-instance information. For
example, both "spam" and "ham" are strings, they are instances of the class
str, but they differ in their per-instance information. Namely, one includes
the four characters s p a m while the other contains three characters h a m.
When you call a str method like this:
>>> s = 'spam' # create a str instance
>>> s.upper()
'SPAM'
how does the upper() method know to return 'SPAM' rather than 'HAM' or
'CHEESE'? It knows, because it has access to the instance 'spam'.
For instances you create yourself, the typical pattern is to write a class
like this:
class Parrot(object):
def __init__(self, name):
self.name = name # Per instance information.
def talk(self):
print "%s wants a cracker." % self.name.title()
>>> polly = Parrot('polly')
>>> alfonse = Parrot('alfonse')
>>> polly.talk()
Polly wants a cracker.
How does the talk method know to print "Polly..." instead of "Alfonse..."?
Because it has access to the specific instance.
But sometimes you have methods that don't care about the per-instance
information, they only care about the class information. For example, the
built-in dict class includes a method "fromkeys" which creates a new
dictionary. It doesn't matter which dict instance you call it from, you get
the same result:
>>> a = {'a': 1}
>>> b = {'B': None, 'c': 42}
>>> a.fromkeys([1, 2, 3])
{1: None, 2: None, 3: None}
>>> b.fromkeys([1, 2, 3])
{1: None, 2: None, 3: None}
In fact, you don't even need to create a dict instance first before calling
fromkeys, you can call it directly from the class itself:
>>> dict.fromkeys([1, 2, 3])
{1: None, 2: None, 3: None}
So the fromkeys method is a class method, and instead of automatically taking
the instance as the first argument (by convention called self), it gets the
class as the first argument (by convention called cls).
Even rarer are cases where the method doesn't care about the instance or the
class. These are called static methods in Python, and are equivalent to pure
functions except they are bound to a class. Static methods don't receive any
automatic arguments, neither the instance nor the class.
(Note: in case you decide to do some googling on this, be aware of the
terminology differences. In Java, a "static method" is what we call a "class
method" in Python; as far as I know, Java doesn't have anything like what we
call a "static method".)
--
Steven
More information about the Tutor
mailing list