why static methods?
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu Feb 20 05:04:51 EST 2003
Tim Peters <tim.one at comcast.net> wrote in
news:mailman.1045689782.11553.python-list at python.org:
> [Gerrit Holl]
>> What is the purpose of static methods? I do not understand the
>> difference with a function outside the class.
>
> Good! That's because there is no difference. It's purely a namespace
> thing. Especially if you define multiple related classes in a single
> module, say A and B, then A.return_something() and
> B.return_something() can be clearer than needing to make up two
> distinct names at the module global level. Defining a static method
> in the class body also gives it easy access to whatever "private
> names" the class may use; writing it outside the class means you'd
> have to simulate Python's name-mangling by hand.
There is another difference in that a static method can be called either
through the class, or through an instance. If you are calling it through an
instance then you can use inheritance and overriding.
Consider the following where the callme method invokes an overridable
static method:
>>> class A:
def method(x):
print "A.method",x
method = staticmethod(method)
def callme(self):
self.method(42)
>>> class B(A):
def method(x):
print "B.method",x
method = staticmethod(method)
>>> A.method(1)
A.method 1
>>> B.method(2)
B.method 2
>>> b1 = B()
>>> b1.method(3)
B.method 3
>>> b1.callme()
B.method 42
>>>
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list