Python Forum
Self - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Self (/thread-20631.html)



Self - sumncguy - Aug-22-2019

Im putting this in homework ... because I am taking a second python class and am still confused with why we use self.

I guess I have a block on this. Can anyone help me with a layman explaination of why we use self.


RE: Self - ichabod801 - Aug-22-2019

The format of calling a method is instance.method(). That's different than calling an unbound function with an instance as a parameter function(instance). The self parameter gives you access to the instance of the class that was used to call the method. That can be used to access the attributes that are particular to that instance. So if you have a bunch of people in a contacts database, and you call the method to get directions to their house, the self parameter is what gets you that particular person's address.


RE: Self - millpond - Aug-26-2019

I have had the same problem, as a n00b.

The way I understyand it is if you have a function in a class, it is not required to use self (static method, vs, self based instance methods). But if it doesnt, it becomes completely contained in its 'scope' and cannot access data not directly passed to it. As a result, it would best be placed *outside* the class.

Self 'attaches' the function to the class and makes it a 'method'. It then has access to the other stuff in the class. It also apparently allows 'instances' (callers) ability to modify or even add to the functions data.

Although my first reaction to it was cruft baggage, in that there should be a default syntax that presumes it, so many other languages use 'self' or similar, that there must be an overriding reason to include this syntax.

There is also a class method which uses cls instead of self, but its beyond me for now!


RE: Self - perfringo - Aug-26-2019

“Layman explanation” could be: self is needed to create instance methods (and differentiate from class methods)

But there is better (but not layman) explanation from Guido van Rossum
Why explicit self has to stay