0

Assume I have some class c, and I would like to create a function f which gets a parameter, which defaults to self.x if not given. i.e.

class c:
   def __init__(self, x):
      self.x = x
   def f(self, n = self.x):
      ...

However, this doesn't seem to work (name 'self' is not defined).

Is there a solution for this problem or is it not possible to use a member as a default for the function?

A simple solution would be something like:

def f(self, n = None):
   if (n is None):
      n = self.x

But I was wondering if it's possible to avoid it.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
R B
  • 543
  • 9
  • 25

1 Answers1

2

Function defaults are determined when the class is built, not when the method is called. At that time there are no instances available to take a default from, no.

You'll have to use a sentinel default here, using None as sentinel as you have done the most common solution used.

If it should be possible to specify None as a value for n, use a different singleton object:

_sentinel = object()

class C:
   def __init__(self, x):
      self.x = x

   def f(self, n=_sentinel):
      if n is _sentinel:
          n = self.x
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343