pythonclassargumentspreset

Argument Preset to Class Variable in Python


class Example:

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

    def function(self, y=self.x):
        pass

Example(72)

When I run this code, I get the following error.

Traceback (most recent call last):
  File "/home/millertime/Desktop/example.py", line 1, in <module>
    class Example:
  File "/home/millertime/Desktop/example.py", line 7, in Example
    def function(self, y=self.x):
NameError: name 'self' is not defined

Evidently, Python isn't happy with having an argument preset to a class variable. Is there a proper way to do this? I know the class info is being passed in the first argument, self. Any way to reference this further along to make my code possible? I've tried changing y=self.x to y=x, but as I suspected this just threw a NameError. I'm well aware of other ways to do this inside the function, but I'm interested if it's possible or not.


Solution

  • In python, the expressions in default arguments of functions are calculated when the function is defined, not when it's called. In the case above there won't be any instantiation hence the error.

    You can do this instead

    class Example:
    
        def __init__(self, x):
            self.x = x
    
        def function(self, y=None):
            if y is None:
               y=self.x
            pass
    
    Example(72)