Newbie: Return value semantics; copy or reference?

Michael Jørgensen ingen at ukendt.dk
Wed Feb 25 13:41:58 EST 2004


Hi all,

I thought that return values in Python are copies and not references.
However, I've run into a problem, which I've isolated to the following code
fragment below.

I observe that the assignment to bpduReceived2 actually changes the value of
bpduReceived1. This is completely unexpected.

I can easily fix the program in a number of different ways. However, I fear
that I'm just pushing the problem in front of me, unless I understand what
is going on.

It seems that the two Frame objects get initialized with the *same* Bpdu
object. Why is that, and how do I make certain it doesn't happen.

-Michael.

================================

class Bpdu:
        def __str__(self):
                return str(self.var)
        def decode(self, input):
                self.var = ord(input[0])

class Frame:
        def __init__(self, _bpdu=Bpdu()):
                self.bpdu = _bpdu

        def decode(self, input):
                self.bpdu.decode(input)

class TestingStation:
  def ReceiveBpdu(self, input):
    frame = Frame()             # Create a placeholder
    frame.decode(input)         # Do the conversion
    print repr(frame.bpdu)
    return frame.bpdu           # Return the converted data.

station1 = TestingStation()
station2 = TestingStation()

bpduReceived1 = station1.ReceiveBpdu("\01")

print "bpduReceived1=", bpduReceived1
print
bpduReceived2 = station2.ReceiveBpdu("\02")    # This line changes
bpduReceived1
print

print "bpduReceived1=", bpduReceived1
print "bpduReceived2=", bpduReceived2
print






More information about the Python-list mailing list