Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Self
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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!
Reply
#4
“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
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


Forum Jump:

User Panel Messages

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