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?
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?
I do not know if this can help you!
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)'