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
Prune
  • 76,765
  • 14
  • 60
  • 81
Ethr
  • 431
  • 1
  • 3
  • 17

2 Answers2

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
John Gordon
  • 29,573
  • 7
  • 33
  • 58
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?

Prune
  • 76,765
  • 14
  • 60
  • 81