[Tutor] static methods and class methods

Marilyn Davis marilyn at deliberate.com
Wed Jun 11 06:41:54 CEST 2008


On Tue, June 10, 2008 9:17 pm, Christopher Spears wrote:

> I am reading  Wesley Chun's "Core Python Programming" (2nd Edition) and
> have  reached the part on static and class methods.  I typed in the
> following to demonstrate the difference between the two methods:
>
>>>> class TestClassMethod:
> ...     def foo(cls):
> ...         print 'calling class method foo()'
> ...         print 'foo() is part of class:',cls.__name__
> ...     foo = classmethod(foo)
> ...
>
>
>>>> class TestStaticMethod:
> ...     def foo():
> ...         print 'calling static method foo()'
> ...     foo = staticmethod(foo)
> ...
>
>>>> tsm = TestStaticMethod() TestStaticMethod.foo()
>>>>
> calling static method foo()
>>>> tcm = TestClassMethod() TestClassMethod.foo()
>>>>
> calling class method foo() foo() is part of class: TestClassMethod
>>>> tcm.foo
> <bound method classobj.foo of <class __main__.TestClassMethod at
> 0xb7da0f2c>>
>
>>>>
>
> According to the author, the result for typing in 'tcm.foo' is

You forgot to put () after the method name.  Wesley has them.

Class methods and static methods can be called, even when you don't have
an instance of the class.

I think that that's all there is to it.

With the class method, the interpreter provides the class itself as the
first argument.  With the static, nothing comes in.

What else?

Marilyn Davis

>
>
> calling class method foo() foo() is part of class: TestClassMethod
>
> Did I do something wrong or is this an error on the book's part?
> Intuitively, the answer I received makes more sense to me.  I am still
> unsure of the difference of static and class methods.  Can someone
> enlighten me?
>
> Thanks!
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list