Default method arguments

Duncan Booth duncan.booth at invalid.invalid
Wed Nov 16 10:48:47 CET 2005


Steven D'Aprano wrote:
> I would like to see _marker put inside the class' scope. That prevents
> somebody from the outside scope easily passing _marker as an argument
> to instance.f. It also neatly encapsulates everything A needs within
> A. 

Surely that makes it easier for someone outside the scope to pass in 
marker:
 
 class A(object):
     _marker = []
     def __init__(self, n):
         self.data =n
     def f(self, x = _marker):
         if x is self.__class__._marker:
             # must use "is" and not "=="
             x = self.data
         print x
 
 >>> instance = A(5)
 >>> instance.f(instance._marker)
 5

What you really want is for the marker to exist only in its own little 
universe, but the code for that is even messier:

class A(object):
    def __init__(self, n):
        self.data =n
    def make_f():
        marker = object()
        def f(self, x = _marker):
            if x is _marker:
                x = self.data
            print x
        return f
    f = make_f()

    
>>> instance = A(6)
>>> instance.f()
6




More information about the Python-list mailing list