Class Methods help

bd satish bdsatish at gmail.com
Sun May 31 09:48:25 EDT 2009


Thanks to Tim Chase & Lie Ryan !!  That was exactly what I was looking for !!

It's time for me to now read the documentation of "decorators" and
@classmethod and also @staticmethod.

I'm quite new to decorators...


-- Satish BD


On Sun, May 31, 2009 at 4:44 PM, Lie Ryan <lie.1296 at gmail.com> wrote:
> bdsatish wrote:
>> Hi,
>>
>>     I have a question regarding the difference b/w "class methods" and
>> "object methods". Consider for example:
>>
>> class  MyClass:
>>     x = 10
>>
>> Now I can access MyClass.x -- I want a similar thing for functions. I
>> tried
>>
>> 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" ??
> with staticmethod decorator:
>
>>>> class MyClass:
> ...     @staticmethod
> ...     def some_func(x):
> ...         return x+2
> ...
>>>> MyClass.some_func(10)
> 12
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list