Unexpected behavior of read only attributes and super

Samuel M. Smith smithsm at samuelsmith.org
Wed Dec 7 10:51:33 EST 2005


On 06 Dec, 2005, at 20:53, Steven Bethard wrote:

> Samuel M. Smith wrote:
>> The dict class has some read only attributes that generate an   
>> exception
>> if I try to assign a value to them.
>> I wanted to trap for this exception in a subclass using super but it
>> doesn't happen.
>>
>> class SD(dict):
>>    pass
>>
> [snip]
>> s = SD()
>> super(SD,s).__setattr__('__iter__', True)
>>
>> Expecting to get the ReadOnly exception but I don't get the  
>> exception.
>
> Note that __iter__ is on the dict *type* not dict instances.  Try  
> this:
>
> py> class SD(dict):
> ...     pass
> ...
> py> super(SD, SD).__init__ = False
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> AttributeError: 'super' object attribute '__init__' is read-only
>
> You can always shadow class-level attributes in the instance dict.
> (That's what you were doing.)  If you want to (try to) replace an
> attribute in the class dict, you need to use the class object, not an
> instance object.
>

I guess that's where my understanding breaks down. I thought the only  
way to access class attributes was by
calling the class directly as your example indicates but __iter__ is  
a class attribute that I can access from the instance
at least to read it. So what determines which class attributes get  
copied to the instance and which ones don't?



More information about the Python-list mailing list