0

I am writing a class in Python3 and want a method to take a default self variable when no explicit value is given. For some reason this doesn't seem to work.

For example, the following code would produce a NameError: name 'self' is not defined error for the 5th line.

class A:
    def __init__(self, a):
        self.a = a

    def func(self, b=self.a):
        pass

Is there a way around this if I want to make my function behave in the manner I specified?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
domoremath
  • 555
  • 2
  • 8
  • 17

1 Answers1

0

This might be what you want.

If func is invoked without a parameter then b would be set to the value of self.a.

class A:
    def __init__(self, a):
        self.a = a

    def func(self, b=None):
        if not b:
            b = self.a
        pass
Bill Bell
  • 21,021
  • 5
  • 43
  • 58