classmethod & staticmethod

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Tue Jul 24 03:58:21 EDT 2007


On Tue, 24 Jul 2007 03:19:05 +0000, james_027 wrote:

> python's staticmethod is the equivalent of java staticmethod right?

Correct.  `staticmethod` is essentially just a function moved into a class
and accessible at the class object and instances of that class.

As Python opposed to Java has functions, `staticmethod` isn't that useful.

> with classmethod, I can call the method without the need for creating
> an instance right? since the difference between the two is that
> classmethod receives the class itself as implicti first argument. From
> my understanding classmethod are for dealing with class attributes?

It's possible to access class attributes and, maybe more important, it's
possible to call the class to return an instance.  So if you call a
`classmethod` on a subclass an instance of that subclass is returned. 
Silly example:

class A(object):
    def __init__(self, x, y):
        print 'init A'
        self.x = x
        self.y = y
    
    @classmethod
    def from_str(cls, string):
        return cls(*map(float, string.split(',')))


class B(A):
    def __init__(self, x, y):
        print 'init B'
        A.__init__(self, x, y)


def main():
    B.from_str('42,23')

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list