Class-level variables - a scoping issue

Chris Rebert clp2 at rebertia.com
Mon Oct 11 13:00:54 EDT 2010


On Mon, Oct 11, 2010 at 9:44 AM, Dennis Lee Bieber
<wlfraed at ix.netcom.com> wrote:
> On Mon, 11 Oct 2010 10:43:04 -0400, John Posner <jjposner at optimum.net>
> declaimed the following in gmane.comp.python.general:
>> No surprising behavior, just a surprising look:
>>
>>    self.EGGS = ...
>>
>> ... which might remind the programmer what's going on -- the redefining
>> of a "constant". This was just a suggestion; I hoped it might be helpful
>
>        But if it is supposed to be a "constant" defined at the class level,
> it would be better to just not use the instance (self.) when referencing
> it. By stuffing the class name into the reference it is even more
> explicit that this is a class level attribute and not an instance
> attribute, and probably shouldn't be changed.

Yes, however that's
(1) likely slightly slower due to the global lookup for the class name
(2) brittle WRT inheritance; subclasses can't override the value
(3) brittle WRT class renaming/refactoring, unless you use
self.__class__.CONSTANT, which is uglier

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list