Freeze in Python?

前端 未结 2 1420
攒了一身酷
攒了一身酷 2021-01-04 06:52

I have programmed in Python for a while, and just recently started using Ruby at work. The languages are very similar. However, I just came across a Ruby feature that I don\

相关标签:
2条回答
  • 2021-01-04 07:29
    >>> a = [1,2,3]
    >>> a[1] = 'chicken'
    >>> a
    [1, 'chicken', 3]
    >>> a = tuple(a)
    >>> a[1] = 'tuna'
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        a[1] = 'tuna'
    TypeError: 'tuple' object does not support item assignment
    

    Also, cf. set vs. frozenset, bytearray vs. bytes.

    Numbers, strings are immutable themselves:

    >>> a = 4
    >>> id(a)
    505408920
    >>> a = 42        # different object
    >>> id(a)
    505409528
    
    0 讨论(0)
  • 2021-01-04 07:47

    You could always subclass list and add the "frozen" flag which would block __setitem__ doing anything:

    class freezablelist(list):
        def __init__(self,*args,**kwargs):
            list.__init__(self, *args)
            self.frozen = kwargs.get('frozen', False)
    
        def __setitem__(self, i, y):
            if self.frozen:
                raise TypeError("can't modify frozen list")
            return list.__setitem__(self, i, y)
    
        def __setslice__(self, i, j, y):
            if self.frozen:
                raise TypeError("can't modify frozen list")
            return list.__setslice__(self, i, j, y)
    
        def freeze(self):
            self.frozen = True
    
        def thaw(self):
            self.frozen = False
    

    Then playing with it:

    >>> from freeze import freezablelist as fl
    >>> a = fl([1,2,3])
    >>> a[1] = 'chicken'
    >>> a.freeze()
    >>> a[1] = 'tuna'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "freeze.py", line 10, in __setitem__
        raise TypeError("can't modify frozen list")
    TypeError: can't modify frozen list
    >>> a[1:1] = 'tuna'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "freeze.py", line 16, in __setslice__
        raise TypeError("can't modify frozen list")
    TypeError: can't modify frozen list
    >>>
    
    0 讨论(0)
提交回复
热议问题