开发者

Python make method immutable

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 开发者_StackOverflowI make the method return the original list?


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.


have getnames return a copy:

def getnames(self):
    return self.names[:]


The name a refers to the same array that's stored in ob.names. If you change a, you change ob.names, because they both refer to the same thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜