Class Methods help

Tim Chase python.list at tim.thechases.com
Sun May 31 15:43:48 CEST 2009


> class MyClass:
>     def  some_func(x):
>         return x+2
> 
> When I call MyClass.some_func(10) -- it fails, with error message:
> 
> 
> TypeError: unbound method some_func() must be called with MyClass
> instance as first argument (got int instance instead)
> 
> OK. I figured out that something like this works:
> obj = MyClass()
> y = obj.some_func(10)
> 
> BUT, this means that we have functions applying for instances. That is
> we have "instance method". Now, how do I implement some function which
> I can invoke with the class name itself ? Instead of creating a dummy
> object & then calling.... In short, how exactly do I create "class
> methods" ??

You mean the classmethod decorator? :)

   class MyClass:
     @classmethod
     def some_func(cls, x):
       return x+2

   MyClass.some_func(42)

(the decorator syntax was added in 2.4, so if you need it in 
pre-2.4, you'd have to do

   class MyClass:
     def some_func(cls, x):
       return x+2
     some_func = classmethod(some_func)

to get the same behavior)

-tkc





More information about the Python-list mailing list