Python Forum
Understanding the "self" concept
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding the "self" concept
#5
As someone who recently got an idea of this, I'll explain how I figured it out without any jargon.

Basically all the self stuff is telling a bit of code what I can see and what it is part of. When you are putting "self" inside the "()" like def do_stuff(self): you are telling that function/class/method that it knows and can "see" anything that the "self" can see. The confusion comes from the fact the "self" here is NOT "do_stuff" but whatever layer or function contains "do_stuff". I'll show you.

I wrote this example, because using "self" all over the place was plain confusing. First example is how you would actually write it, and the second is changed to show what each "self" really means to help understand.
Class Example_class:

    def __init__(self):
        self.something = "something"
        self.another_thing = "another thing"

    def class_method(self):
        print(self.something, self.another_thing)

        def sub_method(self):
            print("la la la")

            def sub_sub_method(self):
                print("Epstein didn't kill himself")
Class Example_class:

    def __init__(Example_class):
        Example_class.something = "something"
        Example_class.another_thing = "another thing"

    def class_method(Example_class):
        print(Example_class.something, Example_class.another_thing) 

        def sub_method(class_method):
            print("la la la")

            def sub_sub_method(sub_method):
                print("Epstein didn't kill himself")
Note that really its just each level telling its children what they can see. That's how from the global level you can run things like
Example_class.class_method.sub_method.sub_sub_method()
Passing the "self" along is creating a trail for python to follow when you ask it to do something.

Hope I didn't confuse you more, it is not the easiest thing to understand or explain.
Reply


Messages In This Thread
Understanding the "self" concept - by peace - Feb-07-2020, 01:26 PM
RE: Understanding the "self" concept - by puredata - Feb-07-2020, 03:42 PM
RE: Understanding the "self" concept - by perfringo - Feb-07-2020, 05:18 PM
RE: Understanding the "self" concept - by metulburr - Feb-07-2020, 05:27 PM
RE: Understanding the "self" concept - by michael1789 - Feb-07-2020, 08:38 PM
RE: Understanding the "self" concept - by peace - Feb-08-2020, 04:44 PM
RE: Understanding the "self" concept - by nilamo - Feb-10-2020, 08:21 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Generating a student's transcript [OOP concept] aongkeko 2 2,747 Dec-01-2020, 06:43 AM
Last Post: buran
  Help learning a concept Ccjake 2 2,418 Jan-22-2019, 01:35 AM
Last Post: Ccjake

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020