Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python make method immutable

Tags:

python

I have the following code:

class Hello(object):
    def __init__(self, names):
        self.names = names
    def getnames(self):
        return self.names  

if __name__ == "__main__":
    names = ['first', 'middle', 'last']     
    ob = Hello(names)
    a = ob.getnames()
    print a
    a.remove('first')
    print a
    print ob.getnames()

The following is the output:

['first', 'middle', 'last']
['middle', 'last']
['middle', 'last']

Is it because the method getnames is mutable? Or may be there is something else going on here. Can anyone explain? How do I make the method return the original list?

like image 832
user955632 Avatar asked Jan 29 '26 05:01

user955632


2 Answers

In Python, assignment never makes a copy of a data structure. It only makes a name refer to a value. Also, function invocation essentially assigns the actual arguments to the argument names. So nothing is copied in your code. The names a and ob.names refer to the same list. If you want to have two copies of the list (the original and one to modify), then you need to make a copy at some point. You'll have to decide where that makes the most sense.

You can copy a list a few different ways: list(L) or L[:] are the most common ways.

like image 75
Ned Batchelder Avatar answered Jan 30 '26 22:01

Ned Batchelder


have getnames return a copy:

def getnames(self):
    return self.names[:]
like image 37
Dan D. Avatar answered Jan 30 '26 20:01

Dan D.