I am a newcomer to Python. I don’t understand how/why the self argument is used:
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()
This code is from a Byte of Python. This code could have just as easily been written as:
def sayHi(self, name):
print 'Hello, my name is', name
p = Person('Swaroop')
p.sayHi()
…right? What is the purpose of making name a field of self?
It seems you are oversimplifying a not so simple thing.
In object-oriented programming, a Class is a Declarative Construct which gives a blueprint as to what an object (a manifestation of this blueprint) would contain (properties) and how it would behave (members).
Every manifestation of such a Class is called an Object which has a defined and specific instance. From an object via any of this behavioral attributes called member functions/methods we need somehow to refer to that instance of the object and remember individual elements within it and make a clear distinction with the other non member entities.
Consider Your example
Every Instance of this Person (Tom, Dick, Harry) is unique and within each instance, to refer back to itself we need some idiom like (self in Python, this ptr is C++ or this in Java).
So in the
__init__method when you need to demarcate between thenameattribute of Person with thenameparameter we can easily do so withself. Not only that, at any instance we can keep on referring back to this name via theself.Making an instance of Person
p=Person('Swaroop')and then invoking sayHi contrasting to calling just a function sayHi which is not a part of an object has two implicationssayHiof the instance of Person named Swaroop on the other hand would mean something like a physically existing Swaroop greeting back his Name who has a persistent memory and would never forget unless he adopts a new name.If you have a background of C++ and might be wondering why on earth do we need to add that extra parameter to the function call where as in C++ this pointer is never passed.
Well Candidly speaking it does. If you read the C++ calling convention, whether X86 or X64, the this pointer is passed through the register
ecxto the method to give an handle to itself. This is more explicit here where we deliberately pass the handle to the current instance to the method.