class method vs static method
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Tue Nov 21 04:13:38 EST 2006
In <1164098781.577358.90850 at 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
More information about the Python-list
mailing list