Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading