classmethod & staticmethod

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Jul 21 07:47:23 EDT 2007


Alex Popescu a écrit :
> Bruno Desthuilliers <bruno.42.desthuilliers at wtf.websiteburo.oops.com> wrote 
> in news:46a5b2ad$0$18903$426a74cc at news.free.fr:
> 
> 
> 
>>[snip...]
>>
>>
>>Not necessarily - you can access class attributes from within an 
>>instance method (but obviously a classmethod cannot access instance 
>>attributes).
>> 
> 
> What I am doing wrong here then:
> 
> class MyClass(object):
>   class_list = ['a', 'b']
> 
>   def instance_method(self):
>     print "instance_method with class list %s" % class_list
> 
> o = MyClass()
> o.instance_method()
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 4, in instance_method
> NameError: global name 'class_list' is not defined

The answer is in the error message. There's no local definition of 
'class_list' in function 'instance_method', and no global definition of 
'class_list' in the module. If you want to access MyClass.class_list in 
function instance_method, you need to use a fully qualified name, ie 
either self.class_list[1], self.__class__.class_list[2], 
type(self).class_list[3] or MyClass.class_list[4]

[1] this one is ok in 'read mode' since attributes not found in the 
instance's __dict__ will be looked up in the class's __dict__ (and then 
in parent's classes __dict__), but be warned that something like 
'self.class_list = []' will create an instance attribute of the same 
name, shadowing the class one. This is one of the (in)famous Python gotchas.

[2] && [3] Those two ones are equivalent. [3] is cleaner since it avoids 
direct access to an implementation attribute, but [2] is faster since it 
avoids a function call. In both cases, the lookup will be what one would 
expect in OO, that is first on the concrete class, then in the parents 
classes.

[4] Only use this one if you really want to bypass inheritance.




More information about the Python-list mailing list