[Tutor] A question about the self and other stuff

Luke Paireepinart rabidpoobear at gmail.com
Mon Oct 26 04:10:57 CET 2009

On Sun, Oct 25, 2009 at 8:06 PM, Khalid Al-Ghamdi <emailkgnow at gmail.com>wrote:

> Hi everybody,
> So I'm new to python and have questions about the following code:
>     def __init__(self, name):
>         '''initializes the data'''
>         self.name=name
>         print ('initializing {0}'.format(self.name))
> 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.

Self refers to the object currently being created by the "init" method, so
it is always the first parameter to __init__.  You can call it 's' or
'foobar' or 'self' or 'cantaloupe', it doesn't matter.  It's just always the
first argument.
"self.name = name" means "take the second argument that is passed to the
__init__ method and assign it to the current object under the "name"
Imagine if you were constructing a car.

class Car(object):
    def __init__(self, doors, chassis):
        self.doors = doors
        self.chassis = chassis

You are passing these parameters to the car so that they can be applied to
the specific car.
For example, you could then do
mychassis = "Dodge Ram"
doors1 = "hatchback"
doors2 = "4-door"
car1 = Car(mychassis, doors1)
car2 = Car(mychassis, doors2)

Is that a little bit more clear?

> 2- in the final few lines where I assign an object to the class, I notice
> that a parameter was entered in the class name, "Robot(D23)", although when
> defining the class I didn't put any arguments for it.
Yes you did,
__init__ takes 2 parameters, "self" and "name".  When constructing a new
object via Robot(D23) you are implicitly passing "self" and you are
explicitly passing 'D23' as "self".

> 3- what is the difference between all the underscore, underscore attributes
> like:__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__',
> '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__',
> '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
> '__setattr__

They all do different things, I'm not sure what you mean by "what are the
They are functions that are called in certain situations.  For example,
a + b
will call

a['blah'] = b
will call

(these __ names may be wrong so don't quote me on them.)

> and the rest of the normal methods for a class.?

Depends on the class.  There are no "normal methods", the methods that a
class has are based upon the type of class it is.  You could have a class
with no methods and only attributes (but this would be almost completely

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091025/b1f7fbc1/attachment.htm>

More information about the Tutor mailing list