October 27th, 2004, 11:02 PM
Unclear abt 'self'!
I wanted to get a clearer definiton of 'self' which is used in classes...cld anyone do it??
Thanks & Rgds!
October 27th, 2004, 11:49 PM
self is traditionally used by a class to refer to an instance of itself. It is similar to the this pointer in C++/java and the self keyword of Delphi. The one difference is that Python doesn't reserve the word 'self' as a keyword and you could use any other variable name in place of 'self' and it would work fine, though the python convention is to use 'self'. In the below code, note that func2() uses 'myvar' as the first argument, but the code does the same thing as func().
As to what self does, when you call x.func(), the value of self within func() will be set as a reference to x. When you call y.func(), the value of self within func() will be set as a reference to y. Thus, you can see that 'self' is set to point to the instance of the variable that called func().
def func(self, val):
self.somevalue = val
def func2(myvar, val):
myvar.somevalue = val
x = myclass()
y = myclass()
Last edited by Scorpions4ever; October 28th, 2004 at 09:30 AM.
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne
"I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
October 28th, 2004, 12:55 AM
Thanks Scorpy for that crash course on 'self'. It is indeed like the 'this' pointer ...but as far as my knowledge goes...the 'this' pointer is an hidden parameter...not explicitly specified. I understood that 'self' has to be the first argument... can have any name... n its mandatory. Now I've got one more question....is _init_ like constructor???
Thanks & Rgds,
October 28th, 2004, 01:58 AM
it's the closest thing to a constructor, since it's the first piece of code run in an instance of a class, but its not because the object has already been constructed by the time __init__ is called, and you already have a valid reference to the new instance of the class.
October 28th, 2004, 06:47 AM
In Python, the construction of the instance is preformed by __new__() and then as Ether said __init__() is called, along with any arguments used in initialisation. You could easily think of it as being a constructor in the basic C/C++ sense of the word, since it is used for the same kind of things, but there are some differences. Nothing worth worrying about though .
You won't usually overwrite __new__(), though you can if you need to! For an example of this being done check out Grims ptypes module:
Nice explanation of self scorp!
October 28th, 2004, 11:18 PM
And hey thanks Mr.moderator for the links & also for introducing me to __new__
Its rightly said instead of wading thru' zillions of books if one talks to a person having a good knowledge abt the subject...one can learn a lot!!!