classmethod & staticmethod

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Jul 24 19:21:22 EDT 2007


On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote:

> Neil Cerutti <horpner at yahoo.com> wrote in
> news:slrnfaccgl.1gk.horpner at FIAD06.norwich.edu: 
> 
>> On 2007-07-24, Alex Popescu <nospam.themindstorm at gmail.com> wrote:
>>> Bruno Desthuilliers <bruno.42.desthuilliers at wtf.websiteburo.oops.com>
>>> wrote in news:46a5b2ad$0$18903$426a74cc at news.free.fr:
>>>
>>
>> [snip...]
>>
>>>
>>> class MyClass(object):
>>>   class_list = ['a', 'b']
>>>
>>>   def instance_method(self):
>>>     print "instance_method with class list %s" % class_list
>> 
>> There's no implicit self or class for Python identifiers.
>> 
>> The name class_list must be quailified: self.class_list or
>> MyClass.class_list.
>> 
> 
> After more investigation I have figured this out by myself, but thanks for 
> the details.
> Now I am wondering if in the above case there is a prefered way:
> MyClass.class_list or self.__class__.class_list? (IMO the 2nd is more safe 
> in terms of refactorings).

Consider what happens when you sub-class:

class MyClass(object):
    class_list = [1, 2, 3]
    def method(self, x):
        return sum(MyClass.class_list) + x

class MySubclass(MyClass):
    class_list = ['a', 'b', 'c'] # over-ride the class attribute

expecting_a_string = MySubclass().method('x')


Use a direct reference to MyClass.class_list when you want a direct
reference to MyClass regardless of which instance or class you are calling
from.

Use self.class_list when you want to use inheritance.

Use self.__class__.class_list when you have an instance method and you
need the class it belongs to.

Use a classmethod and the first argument (by convention called klass
or cls) when you don't care about the instance and just want the class.



-- 
Steven.




More information about the Python-list mailing list