用Python冻结吗? [英] Freeze in Python?

查看:148
本文介绍了用Python冻结吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用Python编程了一段时间,最近才开始在工作中使用Ruby.语言非常相似.但是,我只是遇到了一个不知道如何在Python中进行复制的Ruby功能.这是Ruby的freeze方法.

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't know how to replicate in Python. It's Ruby's freeze method.

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中模仿它?

Is there a way to imitate this in Python?

我意识到我使它看起来似乎只用于列表.在Ruby中,freezeObject上的方法,因此您可以使任何对象不可变.对于造成的困扰,我深表歉意.

I realized that I made it seem like this was only for lists; in Ruby, freeze is a method on Object so you can make any object immutable. I apologize for the confusion.

推荐答案

您始终可以将list子类化,并添加冻结"标志,该标志将阻止__setitem__做任何事情:

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

然后玩:

>>> 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
>>>

这篇关于用Python冻结吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆