class method vs static method

C

Chris Brat

Hi,

I've done some reading up but I cant get my head around how/why class
methods can be used as apposed to static methods.

Can anyone give an example of where they have used class methods?

Thanks,
Chris
 
M

Marc 'BlackJack' Rintsch

Chris Brat said:
I've done some reading up but I cant get my head around how/why class
methods can be used as apposed to static methods.

Can anyone give an example of where they have used class methods?

----
class Spam(object):
def __init__(self, data):
self.data = data

@classmethod
def load(cls, filename):
# Open file and load data.
data = 'eric'
return cls(data)

class Ham(Spam):
pass

ham = Ham.load('test.dat')
print type(ham)
----

Here the type of `ham` is ``<class '__main__.Ham'>`` because a class
method will receive the class on which the method is called as first
argument. In a static method you don't know if it is called on the class
where the method is defined or on a subclass.

Ciao,
Marc 'BlackJack' Rintsch
 
M

Michele Simionato

Chris said:
Hi,

I've done some reading up but I cant get my head around how/why class
methods can be used as apposed to static methods.

Can anyone give an example of where they have used class methods?

Thanks,
Chris

Class methods are typically used as factories:

class MyClass(object):
@classmethod
def myfactory(cls):
self = cls()
initialize(self)
return self

With different factories you can obtain instances of the same classes
initialized in different ways. This is probably better than writing a
lot of subclasses
with different __init__s. This is my typical use case, but I am sure
others will post
many other examples of application.

Michele Simionato
 
B

Bruno Desthuilliers

Chris said:
Hi,

I've done some reading up but I cant get my head around how/why class
methods can be used as apposed to static methods.

a "static method" is actually not much more than a plain function
living in a class's namespace. classmethods, OTOH, have access to the
class object.
Can anyone give an example of where they have used class methods?

The canonical use case is factory methods, but you'll typically find
other possible applications in frameworks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,190
Latest member
ClayE7480

Latest Threads

Top