0

Possible Duplicate:
python 'self' explained

I am a beginner in Python. I was going through the tutorials on Classes and Iterators when I had a doubt that I was unable to explain to myself. The program text below was a part of a class which calculates area.

def __init__(self,len,wid):
    self.length=len
    self.width=wid

def calculate_area(self)
    return self.length*self.width

def print_area(self)
    print 'Area='+str(self.calculate_area())

What I am unable to understand is why do the function's argument list have "self"? What is its role? Why are every variable resolved with "self"?

Community
  • 1
  • 1
Abhinav
  • 992
  • 2
  • 11
  • 26

2 Answers2

2

This is similar to this pointer in C++ (if you have come from C++ background) Typical usage would be that the members of objects can be referenced by self in case if there is an ambiguity. e.g.

def calculate_area(self, length)
    return self.length*self.width

Above length is an argument for calculate_area function. if the object also has length member then it can be resolved by using self.length

Refer existing answer here:

What is the purpose of self?

Community
  • 1
  • 1
Vinayak Kolagi
  • 1,831
  • 1
  • 13
  • 26
  • 1
    You mean the local variable inside area is resolved by self.length so that the compiler understands this is a variable local to the function? – Abhinav Jul 18 '12 at 09:36
0

I really don't know I'm too new on the Python world but I think that Python does not provide the this value as C# or Java do, so this is the mechanism that Python use to define itself in its classes.

Anyway you can see that you don't need to pass the self as parameter in the function call, because Python does for you.

This is my theory, but I'm also interested to know it so If anyone can say more about this, I think we will be very thankfull.

See you!

Amedio
  • 895
  • 6
  • 13