Re: Default method arguments
Steven D'Aprano wrote:[color=blue]
> 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.[/color]
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
[color=blue][color=green][color=darkred]
>>> instance = A(5)
>>> instance.f(inst ance._marker)[/color][/color][/color]
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()
[color=blue][color=green][color=darkred]
>>> instance = A(6)
>>> instance.f()[/color][/color][/color]
6
Steven D'Aprano wrote:[color=blue]
> 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.[/color]
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
[color=blue][color=green][color=darkred]
>>> instance = A(5)
>>> instance.f(inst ance._marker)[/color][/color][/color]
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()
[color=blue][color=green][color=darkred]
>>> instance = A(6)
>>> instance.f()[/color][/color][/color]
6
Comment