Are instances of user-defined classes mutable?

Robin Becker robin at reportlab.com
Thu Aug 6 10:40:54 EDT 2020


On 06/08/2020 05:17, ZHAOWANCHENG wrote:
> the doc of dictionary said "if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key."
> i think a instance of user-defined class is mutable, but i found it can be placed into a tuple that as a key of a dict:
>      >>> class mycls(object):
>      ...     a = 1
>      ...
>      >>> me = mycls()
>      >>> me.a = 2  # mutable?
>      >>> {(1, me): 'mycls'}
>      {(1, <__main__.mycls object at 0x0000022824DAD668>): 'mycls'}
>      >>>
> 
> 
> So are instances of user-defined classes mutable or immutable?
> 
user class instances are clearly mutable, and in my python 3.8 you can do horrid things like this

>>>> class H:
> ...      a = 1
> ...      def __hash__(self):
> ...          return hash(self.a)
> ... 
>>>> h = H()
>>>> hash(h)
> 1
>>>> h.a =2
>>>> hash(h)
> 2
>>>> t=(1,h)
>>>> d={t:23}
>>>> d
> {(1, <__main__.H object at 0x7f5bf72021f0>): 23}
>>>> hash(h)
> 2
>>>> hash(list(d.keys())[0])
> -3550055125485641917
>>>> h.a=33
>>>> hash(list(d.keys())[0])
> -3656087029879219665
>>>> 
so the dict itself doesn't enforce immutability of its keys
--
Robin Becker



More information about the Python-list mailing list