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

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

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?

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


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 :

Neither – you want:

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

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

test = MyClass()
test.process()

All methods need self as an argument.

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