Python Forum
Understanding the "self" concept
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding the "self" concept
#1
Hi community,

I understand that we need to use the "self" keyword everywhere in Python methods.

Still I am not conceptually clear what it means. I would be grateful if you can tell me in your words, why Program2 doesn't work, while Program1 does.

I believe it is important to understand the concept rather than just knowing the rule. Why is the "self" keyword important in Program2? Shouldn't the code search for the method in the Class itself, and search for it in the Superclass if not found?

##Program1
class giveIDCard:
    def issueIDCard(self):
        self.prepareIDCard()
        
class oldEmployees(giveIDCard):
    def prepareIDCard(self):
        self.renewIDCard()

    def renewIDCard(self):
        print('renew ID card')
Output:
>>> s=oldEmployees() >>> s.issueIDCard() renew ID card
##Program2
class giveIDCard2:
    def issueIDCard2():
        prepareIDCard2()
        
class oldEmployees2(giveIDCard2):
    def prepareIDCard2():
        renewIDCard2()

    def renewIDCard2():
        print('renew ID card')
Error:
>>> s=oldEmployees2() >>> s.issueIDCard2() Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> s.issueIDCard2() TypeError: issueIDCard2() takes 0 positional arguments but 1 was given
Reply
#2
looking to understand the same thing, good question, following the thread.
Reply
#3
One way at looking 'self':

>>> s = 'classes'          # instance of the string class ('one string bound to name s')
>>> s.capitalize()         # method on instance of the string class (function in class body)
'Classes'
Class method is function applied on class instance. self is representing/describing/stating/annotating this instance.

Of course, it you are interested in ultimate truth, then read Guido van Rossum: Why explicit self has to stay
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
The first parameter in a function of a class is the object itself. When you do not have any parameters, the instance is still passed, but hidden. Unless you make it a static method. This is why the first code runs while the second gets an error.

You can read more about it here
Recommended Tutorials:
Reply
#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
#6
OP - you do not need to include self in every function or method definition, only those that are part of classes. For free standing functions, the following is fine -
def fnA(first, second) :
    return first*second

fnA(4,7)
Output:
28
But, if you want to use a class based method you will need to use self. Then, the method is able to use all of the internal object values and methods -
class Foo :
    def __init__(self):
        pass

    def fnA(self, first, second) :
        return first*second + self.data1/self.data2

bar = Foo()
bar.data1 = 6
bar.data2 = 3
print(bar.fnA(4,7))
barrio = Foo()
barrio.data1 = bar.data1-1
barrio.data2 = 17
print(barrio.fnA(6,10))
The class is defined, a class method is defined. We then create 2 instances of the class (bar and barrio), and execute the method in each of the instances.

Self gives the function access to the items within the instance of the class.
Reply
#7
(Feb-07-2020, 05:27 PM)metulburr Wrote: The first parameter in a function of a class is the object itself. When you do not have any parameters, the instance is still passed, but hidden. Unless you make it a static method. This is why the first code runs while the second gets an error.

You can read more about it here
Thank you for your time and response!

(Feb-07-2020, 08:38 PM)michael1789 Wrote: 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.
thank you for your time and response, this helps!
Reply
#8
A class is sort of a blueprint or a template for making things. The self parameter is a reference to a specific instance of that template.

For example, let's say we had a Car class:
class Car:
    def __init__(self):
        self.heading = 0
    def turn(self, degrees):
        self.heading += degrees

my_red_pinto = Car()
print(my_red_pinto.heading)
my_red_pinto.turn(45)
print(my_red_pinto.heading)
If I turn my car 45 degrees to the right, that shouldn't turn every car in the world 45 degrees. self is how we tell Python that we only want to interact with that one particular object, instead of all of them in existence.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Generating a student's transcript [OOP concept] aongkeko 2 2,674 Dec-01-2020, 06:43 AM
Last Post: buran
  Help learning a concept Ccjake 2 2,300 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