关于ruby:在Python中冻结?

Freeze in Python?

我用Python编程已经有一段时间了,最近刚开始在工作中使用Ruby。语言非常相似。不过,我刚刚遇到了一个Ruby特性,我不知道如何在Python中复制它。这是Ruby的freeze方法。

1
2
3
4
5
6
7
8
9
10
irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> a[1] = 'chicken'
=>"chicken"
irb(main):003:0> a.freeze
=> [1,"chicken", 3]
irb(main):004:0> a[1] = 'tuna'
TypeError: can't modify frozen array
        from (irb):4:in `[]='

        from (irb):4

有没有一种方法可以在python中模仿这个?

编辑:我意识到我让它看起来像只针对列表;在Ruby中,freezeObject上的一种方法,因此可以使任何对象不可变。我为困惑道歉。


1
2
3
4
5
6
7
8
9
10
>>> 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

同时,比照setvs. vs. bytesfrozensetbytearray

数,字符串是不变的自我。

1
2
3
4
5
6
>>> a = 4
>>> id(a)
505408920
>>> a = 42        # different object
>>> id(a)
505409528


你可以永远list)亚型和"冻结"的旗帜,会做什么:__setitem__

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

然后玩它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> 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
>>>