Style question - defining immutable class data members

Rhodri James rhodri at wildebst.demon.co.uk
Sun Mar 15 14:50:04 EDT 2009


On Sun, 15 Mar 2009 17:55:25 -0000, Aaron Brady <castironpi at gmail.com>  
wrote:

> On Mar 15, 12:39 pm, John Posner <jjpos... at snet.net> wrote:
>> (My apologies if the thread has already covered this.) I believe I  
>> understand the WHAT in this situation, but I don't understand the WHY  
>> ...

[snip]

>> My question is ... WHY does the interpreter silently create the  
>> instance attribute at this point, causing a "surprising decoupling"  
>> from the class attribute? WHY doesn't the interpreter behave as it  
>> would with a simple, non-instance variable:
>>
>>   > python
>>   Python 2.6.1 ...
>>   Type "help", "copyright", "credits" or "license" for more information.
>>
>>   >>> x += 1
>>   Traceback (most recent call last):
>>     File "<stdin>", line 1, in <module>
>>   NameError: name 'x' is not defined
>>
>> Is there a beneficial effect of silently creating the instance  
>> attribute, which outweighs the detrimental effects: (1) inconsistency,  
>> (2) the "surprising" decoupling?
>
> Yes.  If you access an attribute, you want the search to go like this:
>
> - check instance for attribute
> - check class for attribute
> - check base classes for attribute

But do you, though?  The only occasion I can think of that I'd want
the search to go past the instance is this "auto-initialisation",
and frankly I'd rather do that in an __init__ anyway.  Perhaps
static methods or class methods work that way, I don't know how
the innards of the interpreter handle that.

Is there any actual advantage to self.attribute picking up
Class.attribute instead of raising a NameError?

> If you write an attribute, you want it stored in the attribute, not
                                                        ^^^^^^^^^
> the class or base classes.

I think you meant "instance" there :-)  Actually what I want is for
the attribute to be stored where I told it, which could well be in
the class.  If the attribute is specified as "self.attribute", then
yes, put it in the instance.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list