[Tutor] A question about the self and other stuff

Alan Gauld alan.gauld at btinternet.com
Mon Oct 26 10:00:18 CET 2009


"Khalid Al-Ghamdi" <emailkgnow at gmail.com> wrote

> class Robot:
>    population = 0
>
>    def __init__(self, name):
>        self.name=name
>        print ('initializing {0}'.format(self.name))
>        Robot.population+=1
>
>    def __del__(self):
>        '''I'm dying'''
>        print ('{0} is being destroyed!'.format(self.name))
>        Robot.population-=1

> droid1 = Robot('D23')

> 1- In the class definition above, I don't get the "self.name=name". I
> understand that the self is supposed to refer to the actual object, but
> since it is an initialization method, there is no way to enter a name in
> place of the arguments.

When you instantiate a class you create a new object and initialise it.
The way you do that in code is

object = ClassName(arguments)

What then happens is that the ClassName object is created
and its __init__ method is called with arguments passed to it.

So in your case when you do

droid1 = Robot("D23")

you are NOT assigning the class to droid1 you are creating
a new instance of Robot and passing the argument "D23" to
the init method as its name parameter. The __init__ method
then assigns the name to self.name, ie to droid1.name

The __xxx___ methods are all special methods that Python
calls indirectly. __del__ is called when an object is deleted so
is the complement of __init__. __eq__ is called when we do an equality 
test:

if drioid1 == droid2

for example will actually call doid1.__eq__(droid2)

These methods allow us to change how operatrors work for our classes.


You might find it useful to read the OOP topic in my tutorial as
an secondary source to the book/course you are currently reading.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list