'self. | NameError: name 'self' is not defined or NameError: name 'foo' is not defined [duplicate]

I quite often come across this object-oriented programming problem in Python, where I always seem to have both of these approaches fail. I have extensive experience with OOP in other languages, but only now using this in Python.

I want to call-upon a declared variable from __init__(self).

What is/ should be the standard approach?


Invoking self.foo:

class MyClass:
    def __init__(self):
        self.foo = 'value'

    def process():
        print(self.foo)  # !

test = MyClass()

Traceback:

NameError: name 'self' is not defined

Invoking foo:

class MyClass:
    def __init__(self):
        self.foo = 'value'  # `self.` kept here

    def process():
        print(foo)  # !

test = MyClass()

Traceback:

NameError: name 'foo' is not defined


Solution 1:[1]

You need to pass the self argument in every method (when defined in the class) :

class MyClass:
    def __init__(self):
        self.foo = 'value'

    def process():
        print(self.foo)  # `self` is not defined,
                         # you need to give it as argument

Corrected code:

class MyClass:
    def __init__(self):
        self.foo = 'value'

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

Solution 2:[2]

Someone had posted a comment stating:

def process(self)

Where self. needed to be added to the class method which uses any self. var/ obj.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stijn B
Solution 2 DanielBell99