How to create immutable objects in Python?

5

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

    
asked by anonymous 25.09.2014 / 16:36

1 answer

2

I do not know if this can help you!

link

In Python, some built-in types (numbers, booleans, strings, tuples, frozensets) are immutable, but custom classes are often mutable. To simulate immutability in a class, you must override the attribute and exception setting for exception generation:

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)'
    
27.09.2014 / 18:01