0

Could anyone explain, why self.C is returned reversed after execution ?

class Digits:
        def __init__(self, A, B):
            self.C = [0] * 10
            self.A = [1 if digits == '1' else 0 for digits in bin(A)[2:]]
            self.B = [1 if digits == '1' else 0 for digits in bin(B)[2:]]
        def f(self):
            C = [0] * 3
            for i in range(3):
                C[i] = self.A[i] + self.B[i]
            buf = C
            buf.reverse()
            self.C = C
            return buf
var = Digits(6,7)
var.f()
print var.A
print var.B
print var.C

I just reverse buf variable, not C, why var.C reversed too. Sorry I just learning obj-orienting. Thanks.

2 Answers 2

1

Lets explain the reason graphically. enter image description here

Here A and Buf are just the references to same memory location.

buf = C

above will cause buf to also point at same memory location. Theirfore any changes in eighther of them will affect both. This is true in case of object. However in case of primitive data types this does not hold. For example.

a = 5
b = a 
b += 3

Here a will not be affected by change in value of b, because here a and b does not hold the reference of the memory location. They hold actual data

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But how to print var.C and print f() be reverse array of each other?
Thanks, finally it works. But now looks dirty, because of implementing deepcopy from copy =(.
also, without implementing some stuff, I can work with arrays like this: b = a[:]. This will not link both variables to same object.
1

You really only need to look at this sequence here:

            buf = C
            buf.reverse()
            self.C = C
            return buf

On the first line, you set buf = C. Now buf and C are the same object. If you reverse buf, you reverse C too since they are the same object. After the reversal, you do self.C = C. The same thing applies here -- Now self.C is buf (which is C). Last, you return buf, but you've already reset self.C at this point.

Note that in your code if you write something like:

x = var.f()
x[1] = 'Hello World!'
print var.C

You'll see 'Hello World!' in there because the value return from f is var.C.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.