Newbie: Return value semantics; copy or reference?

Mel Wilson mwilson at the-wire.com
Wed Feb 25 21:17:58 EST 2004


In article <403cec0f$0$95081$edfadb0f at dread11.news.tele.dk>,
"Michael Jørgensen" <ingen at ukendt.dk> wrote:
>[ ... ]
>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.



More information about the Python-list mailing list