Newbie: Return value semantics; copy or reference?

M

Michael Jørgensen

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
 
M

Mel Wilson

[ ... ]
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.

The Bpdu object that's used as Frame's default gets
created *once* when the `def __init__` statement gets
executed to create the Frame classes __init__ method. That
is, that Bpdu instance is a permanent feature of
Frame.__init__ . The thing to do is code


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


so that a fresh instance of Bpdu is created for every call
to Frame.__init__ .

If you'd been bitten while trying to create a default list
or dict, this would have been a FAQ.

Regards. Mel.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top