NameError: name 'self' is not defined

PythonNameerror

Python Problem Overview


Why such structure

class A:
    def __init__(self, a):
        self.a = a

    def p(self, b=self.a):
        print b

gives an error NameError: name 'self' is not defined?

Python Solutions


Solution 1 - Python

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It's a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):
    if b is None:
        b = self.a
    print b

Update 2022: Python developers are now considering late-bound argument defaults for future Python versions.

Solution 2 - Python

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

Solution 3 - Python

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name 'self' is not defined

def foo(self):
    print(self.bar)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchrissView Question on Stackoverflow
Solution 1 - PythonintgrView Answer on Stackoverflow
Solution 2 - PythonAndrewView Answer on Stackoverflow
Solution 3 - PythonErichView Answer on Stackoverflow