I'm currently trying to code a program using Object-Oriented Programming and I've run into a problem; what I'm trying to do is use a getter to call for a particular attribute of a particular object as a reference so I can assign it to a variable to manipulate the data without affecting the object (similar to how you could say 'x = [1, 2, 3]' then ' y = x' and be able to manipulate y without affecting x.
However, I'm having the problem that (as far as I can tell) the getter is returning the actual attribute itself (i.e. a reference to the attribute) so that any changes to the variable are also performed on the attribute.
Am I missing something or do I just have to alter the getters to first store the attribute as a variable and then return the variable (because I feel like that's a somewhat ham-handed work around)?
As an example of what I'm trying to say, here's a code that should outline the problem: https://repl.it/@lclarkejhdf/Problem-with-getters
Any help is much appreciated!
y = x does indeed make both the variables point to the same value, and you can even check for it:
- There's the
idfunction, which returns a unique id for every object stored in memory. Call it on both
y, and you'll see that both the variables are actually pointing to that same list.
- There's also the
isoperator, which is quite self-explanatory
>>> x = [1, 2, 3] >>> y = x >>> x is y True >>> x = [1, 2, 3] >>> y = [1, 2, 3] >>> x is y False
Sometimes this stuff can get confusing though, so when you have the time I really recommend this article (15-20 minute read).
You're right about decorators, although they may be the more pythonic way to go about doing things, you should probably stick to your course.
No problem, Cheers!