[Python] Getters causing an object's attributes to be manipulated
lclarkejhdf (11)

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!

You are viewing a single comment. View All
Answered by JustARatherRidi (190) [earned 5 cycles]
View Answer
lclarkejhdf (11)

@JustARatherRidi I never realised that doing 'y = x' when x is a list means that both variables refer to the same list, I guess it's true that you learn something everyday!

Also, I don't know why I explained my workaround the way I did, since the workaround I have actually used is what you suggested using (although I have a for loop that appends each item from the original list to a new list, so I think I'll use you method since that's more concise).

As for decorators, I read about them while trying to find out where I might have been going wrong; I feel like I'll try learning them in future since they're apparently a better way of doing it (or at least that's the impression I'm getting), but for now I'll probably stick to what I have been doing since that's how we've been taught in my course so I want to show that I do understand the method taught before going onto more 'advanced' methods.

Thanks for all the help!