How to create immutable objects in Python?

Asked

Viewed 334 times

5

Based on this question, Is it possible to create your own immutable objects/classes in Python, in the sense that by default, this object of mine will be copied when passed as a function argument? If possible, how to do?

1 answer

2


I don’t know if that can help you!

http://en.wikipedia.org/wiki/Immutable_object

In Python, some embedded types (numbers, booleans, strings, tuples, frozensets) are immutable, but custom classes are usually mutable. To simulate immutability in a class, the attribute configuration and the exclusion for exception generation should be replaced:

class Imutavel(objeto):
    """Uma classe imutável com um único 'valor' de atributo."""
    def __setattr__(self, *args):
        raise TypeError("impossível modificar instância imutável")
    __delattr__ = __setattr__
    def __init__(self, valor):
        # não podemos mais usar self.valor = valor para armazenar dados da instância
        # por isso temos de chamar explicitamente a superclasse
        super(Imutavel, self).__setattr__('valor', valor)`
  • 1

    To be able to use in practice it was useful to also have a method that allows copying the object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.