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?

1
  • I see it is the same as the duplicate. Commented Jan 1, 2018 at 17:51

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.