When we define a variable, we are basically naming a memory address, it follows a script that represents my doubt:
class Spam:
_value = []
@classmethod
def value(cls):
return cls._value
>>> Spam.value()
[]
So far so good, but the problem is that the class method returns a reference to a variable defined up to now as "privada"
, now I can do:
>>> var = Spam.value()
>>> var.append(5)
>>> Spam.value()
[5]
>>> var is Spam.value()
True
In some of the codes I'm reading, they avoid returning a reference to the variable itself, and return a copy of it as follows:
class Spam:
_value = []
@classmethod
def value(cls):
return cls._value.copy()
>>> Spam.value()
[]
>>> var = Spam.value()
>>> var.append(5)
>>> var
[5]
>>> Spam.value()
>>> []
>>> var is Spam.value()
False
Is there any other way to avoid returning the reference in Python?