difference between class and static methods?

Petr Prikryl prikryl at skil.cz
Wed Apr 19 02:30:11 EDT 2006


"John Salerno" wrote...
[...]
> So a class method is specifically for using the class name itself as an
> object in the method? If that's the case, then it makes some sense now.
> I guess the reason I didn't get it before is that this is a feature of
> dynamic languages, right? And something that couldn't have been done in
> C# anyway?

Yes, almost. You can think about a class method as about something that
can be called even if no object of that class was created. It can be called
through the class name. But it can also be called through the instance
(the object). On the other hand, the normal method can be called only
through the object. It does not belong to the class -- see below.

The class method has access to the class variables, but not to the
instance variables (no instance may exists) -- not shown here.

Try the following script (I have stored it as a.py)
---------------------------------------------------
class C:
    def __init__(self):
       print 'Instance of the class C was created.'

    @classmethod
    def myClassMethod(cls):
        print 'myClassMethod called'

    def myMethod(self):
        print 'myMethod (i.e. the normal one) was called.'

C.myClassMethod()

obj = C()
obj.myClassMethod()
obj.myMethod()

C.myMethod()  # cannot be done, error.
---------------------------------------------------

And run it

C:\tmp>python a.py
myClassMethod called
Instance of the class C was created.
myClassMethod called
myMethod (i.e. the normal one) was called.
Traceback (most recent call last):
  File "a.py", line 18, in ?
    C.myMethod()
TypeError: unbound method myMethod() must be called with C instance as first
argument (got nothing instead)

pepr





More information about the Python-list mailing list