On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote: > Neil Cerutti <[EMAIL PROTECTED]> wrote in > news:[EMAIL PROTECTED]: > >> On 2007-07-24, Alex Popescu <[EMAIL PROTECTED]> wrote: >>> Bruno Desthuilliers <[EMAIL PROTECTED]> >>> wrote in news:[EMAIL PROTECTED]: >>> >> >> [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. -- http://mail.python.org/mailman/listinfo/python-list