What am I not understanding about 'self' instance?

Question:

Here is a link to my github: airplane.py

I keep receiving the error:

NameError: name 'self' is not defined

I have looked through countless other stack overflow threads and there is clearly something I am not understanding about the self instance, because it feels like I’ve tried all they have advised. For clarification, the Airplane.__init__(self) at the end is supposed to be outside the class since I want to actually execute the code at this point. If there’s a better way to do so, please let me know, as I suspect that may be the issue.

Asked By: frc_contributor

||

Answers:

When you are outside the scope of your __init__ function of the Airplane class(or another method of that class, which you put self word as an argument while defining), that self word no longer has a meaning(unless you define it to be something else, in your global scope), as it does not exist in the global scope. Thus it won’t recognize what self refers to.

If you want to execute the things you wrote in __init__(self) , just create an instance of that class by:

tmp = Airplane()
Answered By: muyustan

If you have experience with classes in C++ then you can take self to be the equivalent of this in C++.

When you pass self to your Airplane member functions it signifies the current instance of your Airplane class to be used.

class Airplane():

    def __init__(self):
        ### IS INIT? ###
        f = open("log_file.txt", "w")
        f.write("test init")
        f.close()

        ### INSTANTIATE SUBSYSTEMS ###
        left_control_pitch = Left_Control_Pitch(self)
        self.left_control_pitch = left_control_pitch

        ### INITIALIZE SUBSYSTEMS ###
        self.left_control_pitch.__init__()

    def periodic(self):
        ### RUN EXECUTE METHODS ###
        self.left_control_pitch.level()

Here every time you make an Airplane object you can it will execute the code in __init__

For Example

> a1 = Airplane()

"""
You can call the periodic function for a1 like so
"""
a1.periodic()
# Here the self will point to a1
Answered By: sudo97
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.