Default method arguments

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Nov 15 17:28:13 EST 2005


On Tue, 15 Nov 2005 18:44:23 +0100, bruno at modulix wrote:

> Another solution to this is the use of a 'marker' object and identity test:
> 
> _marker = []
> class A(object):
>     def __init__(self, n):
>         self.data =n
>     def f(self, x = _marker):
>         if x is _marker:
>             x = self.data
>         print x

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.

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

Note the gotcha though: in the method definition, you refer to a plain
_marker, but in the method code block, you need to qualify it.


-- 
Steven.




More information about the Python-list mailing list