0

I would like to use element defined in class __init__ as default argument of some other method. Here is my code:

class Main():
    def __init__(self):
        self.value = 3

    def print_element(self, element=self.value):
        print(element)

main = Main()
main.print_element()

It generates error:

Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Main():
  File "so.py", line 5, in Main
    def print_element(self, element=self.value):
NameError: name 'self' is not defined
0

2 Answers 2

2

I don't believe you can use an instance attribute value as a default. You can work around it by defaulting to None, then doing the rest inside the function:

def print_element(self, element=None):
    if element is None:
        element = self.value
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot do this: the default value is evaluated when you define the function.

Your run-time logic appears to be

  • if element is passed in, print that
  • else, print the current self.value

You can get this with a conditional inside the method.

def print_element(self, element=None):

    print(element if element else self.value)

Is that brief enough to suit your purposes?

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.