[Python-de] Re: konstante Lists, Dictionaries
[email protected] (Stefan Ram) 28 Apr 2024 17:58:05 GMT
| Newsgroups | gmane.comp.python.general.german |
|---|---|
| Organization | Stefan Ram |
| Message-ID | <[email protected]> |
[email protected] (Stefan Ram) schrieb oder zitierte: >Allerdings wäre danach >issubclass( const_dict, collections.abc.MutableMapping ) >wahr (/Mutable/!). Dies mag in der hier beschriebenen Anwendung >kein Problem sein; aber um dies zu verhindern, könnte man >"const_dict" auf collections.abc.Mapping bauen. Hier nun eine korrigierte Version: import collections.abc class ImmutableMap( collections.abc.Mapping ): def __init__( self, *args, **kwargs ): self._data = dict( *args, **kwargs ) def __len__( self ): return len( self._data ) def __getitem__( self, key ): return self._data[ key ] def __iter__( self ): return iter( self._data ) def __contains__( self, key ): return key in self._data def get( self, key, default=None ): return self._data.get( key, default ) def __str__( self ): return str( self._data ) print( issubclass( ImmutableMap, collections.abc.MutableMapping )) print( issubclass( ImmutableMap, collections.abc.Mapping )) d = dict() d[ 1 ]= 2 print( d ) c = ImmutableMap( d ) print( c ) c[ 2 ]= 3 Ausgabe: False True {1: 2} {1: 2} Traceback (most recent call last): File "Main.py", line 35, in <module> c[ 2 ]= 3 TypeError: 'ImmutableMap' object does not support item assignment _______________________________________________ python-de Mailingliste -- [email protected] Zur Abmeldung von dieser Mailingliste senden Sie eine Nachricht an [email protected] https://mail.python.org/mailman3/lists/python-de.python.org/ Mitgliedsadresse: [email protected]