By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,994 Members | 1,166 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,994 IT Pros & Developers. It's quick & easy.

class method vs static method

P: n/a
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

Nov 21 '06 #1
Share this Question
Share on Google+
4 Replies


P: n/a
In <11*********************@j44g2000cwa.googlegroups. com>, Chris Brat
wrote:
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
Nov 21 '06 #2

P: n/a

Chris Brat wrote:
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

Nov 21 '06 #3

P: n/a
Chris Brat wrote:
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.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Nov 21 '06 #4

P: n/a
Thanks for the responses - things are clearer now.

Nov 21 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.