share function argument between subsequent calls but not between class instances!

Duncan Booth duncan.booth at invalid.invalid
Sat Feb 18 11:50:54 EST 2006


K. Jansma wrote:

> as you can see, the b.f method shares L with a.f.
> How can I avoid this without using eg. self.L in an __init__?
> 

You cannot.

If a method argument has a default value then the same default is used 
whenever the method is called. If you want each instance to have its own 
value then you must use an attribute on the instance.

If you intend to only use the default some of the time, and at other times 
pass in a different list, then save the 'default' in the instance and use a 
special marker value to indicate when you intend the default to be used:

marker = object()

class Test(object):
    def __init__(self):
        self.L = []

    def f(self,a, L=marker):
        if L is marker:
            L = self.L
        L.append(a)
        return L



More information about the Python-list mailing list