0

I have problem with understanding what happens with the instance variable in the following case:

class Permutation:
    def __init__(self,cycles):
        self.cycles=cycles            

    def inverse(self):
        c=self.cycles
        for i in c:
            r=math.ceil(len(i)/2)
            for j in range(r):
                i[j],i[-(j+1)]=i[-(j+1)],i[j]
        return c

p = Permutation([[1,5,2],[3, 7]])
print(p.cycles)
p.inverse()
print(p.cycles)

output:

>>> 
[[1, 5, 2], [3, 7]]
[[2, 5, 1], [7, 3]]

I have a class named Permutation with instance variable cycles. When I want to calculate the inverse of the permutation, I define new variable c, which should be the same as self.cycles and then I calculate the inverse of variable c. When I create an instance p=Permutation(...) and call p.inverse(), p.cycles actually changes and I'm not sure why.

Could someone please explain what is happening with variable cycles?

Thank you!

user2923638
  • 25
  • 1
  • 5
  • 1
    If you think `c = self.cycles` creates a copy then that's not the case with mutable objects. – Ashwini Chaudhary Jan 27 '15 at 20:25
  • Please show us the exact code that calls `p.inverse()`, with print statements that demonstrate the changes to `p.cycles`. – Kevin Jan 27 '15 at 20:25
  • 1
    @AshwiniChaudhary: immutable objects don't make a copy either, so you can stop at "that's not the case". :-) – DSM Jan 27 '15 at 20:27
  • @DSM Usually some users then ask `x = 1; y = x; y += 1`: why `x` is still 1?. So I try to use the term "mutable objects" to prevent such follow up comments. But, technically you're right. – Ashwini Chaudhary Jan 27 '15 at 20:32
  • I didn't know much about mutable and immutable objects so now I understand. Thank you! – user2923638 Jan 28 '15 at 08:51

0 Answers0