difference between class and static methods?
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Tue Apr 18 17:02:45 EDT 2006
In <gPa1g.1980$No6.43177 at news.tufts.edu>, John Salerno wrote:
> I've been reading up on them, but I don't quite understand how they
> differ in practice. I know how each is implemented, and from C# I
> already know what a static method is. But I won't assume that it's the
> same in Python. And on top of that, both the class and static methods of
> Python seem to do what a C# static method does, so I don't see the
> difference yet.
The difference is that the classmethod gets the class as first argument
much like self in instance methods.
class A:
def __init__(self, data):
print 'A'
self.data = data
@classmethod
def from_file(cls, filename):
# read data
return cls(data)
class B(A):
def __init__(self, data):
print 'B'
self.data = data
If you call `B.from_file('spam.xyz')` now, the `from_file()` method
inherited from class `A` is called but with `B` as the first argument so
it returns an instance of `B`.
A staticmethod is just a function attached to a class without any "magic".
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list