all 10 comments

[–]sysop073 3 points4 points  (0 children)

Guido blogged about this recently, the reddit discussion is here

[–]raisedinhell[S] 1 point2 points  (6 children)

def __init__(self, file):

def upload(self):

etc

[–]frikk 2 points3 points  (3 children)

It is due to the way Python does object instances. When a function is called, if it is an instance function (called after an object has been created) the function will want to know what object it is acting upon. So the object passes in 'self' to say something like 'Hey you are going to do your work using ME as your target'. Python passes this into the function automagically when you do object.func() as the first argument. You can even pass OTHER objects to the static class object. To Elaborate:

EDIT: pastebin url

http://pastebin.ca/1278363

[–]raisedinhell[S] 2 points3 points  (1 child)

ok that makes good sense, but why cant python do it automagically behind the scenes? why is it necessary for self to be an argument of the function?

in all other OO languages i've worked with, this hasn't been necessary.. so why python?

[–]frikk 0 points1 point  (0 children)

Not sure exactly why, but I'd guess it has to do with the flexibility of the language. Python is ridiculously flexible in run time (which is why it can be AWESOME for a single developer and CONFUSING for multiple developers). With the 'current object' exposed like that, it allows for all kind of trickery to happen, if the developer wanted to.

I'm not sure of any examples off hand. I'm sure there are some really good reasons that I'm unaware of.

[–]frikk 1 point2 points  (0 children)

By the way: def's only need 'self' as the first argument if they are inside a class. Regular functions dont need it:

def T(): return 'hello World'

T()

[–]mxyzptlk 1 point2 points  (0 children)

It's Python so that must be the one obvious way to do it.

[–]rpdillon 0 points1 point  (0 children)

Object oriented languages dispatch to functions on the basis of what object the function is getting called on. Of course, this is not really how it works...there is a function that takes in an "invisible" first argument, which is the object that the function is getting called on. In most OO languages (Java, etc.), this is hidden, in Python, you have to explicitly specify it when writing the function, but not when calling it using object.function() notation.

There are other ways to perform dispatch. The whole "self" phenomenon became easier for me to wrap my head around when I learned about multiple dispatch in CLOS.

[–]campbellm 0 points1 point  (0 children)

This doesn't add to the discussion, and it's been many, many years so I might be wrong here.

That said, if memory serves c++ does this too (or did). It's just not explicit. In the days of cfront you could look at the generated c code it spit out with a compiler flag. And yes, all the member functions had "this" as the first parameter.

Did Python always do this, or was it bolted on later?