[Python-Dev] __slots__ and default values
Duncan Booth
duncan@rcp.co.uk
Tue, 13 May 2003 16:20:30 +0100
Aahz <aahz@pythoncraft.com> wrote in news:20030513141719.GA12321@panix.com:
> On Tue, May 13, 2003, Raymond Hettinger wrote:
>>
>> Was there a reason that __slots__ makes initialized variables
>> read-only? It would be useful to have overridable default values
>> (even if it entailed copying them into an instance's slots):
>>
>> class Pane(object):
>> __slots__ = ('background', 'foreground', 'size', 'content')
>> background = 'black'
>> foreground = 'white'
>> size = (80, 25)
>>
>> p = Pane()
>> p.background = 'light blue' # override the default
>> assert p.foreground == 'white' # other defaults still in-place
>
> Why not do the initializing in __init__?
The following works, but I can't remember whether you're supposed to be
able to use a dict in __slots__ or if it just happens to be allowed:
>>> class Pane(object):
__slots__ = { 'background': 'black', 'foreground': 'white',
'size': (80, 25) }
def __init__(self):
for k, v in self.__slots__.iteritems():
setattr(self, k, v)
>>> p = Pane()
>>> p.background = 'blue'
>>> p.background, p.foreground
('blue', 'white')
>>>
--
Duncan Booth duncan@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?