[Tutor] defining __init__

S. D. Rose s_david_rose at hotmail.com
Fri Jan 13 20:54:42 CET 2006


One thing about classes that really tripped me up when I first started using
classes was 'self' before the variable.  When you have '  self.variable  '
that is a variable that can be referenced by the parent.  If there's no
'self' before the variable, you can not.

For instance, if you have a routine:

class Dog:
    def __init__(self, color):
        self.color = color
        age = 16

buster = Dog('black')
buddy = Dog('tan')
roofus = Dog('gray')

print buster.color
print buddy.color
print roofus.color

will yield the text as answers:  black, tan, gray

print buster.age
print buddy.age
print roofus.age

will -*NOT*- yield 16, 16, 16.  It will error out, because you can not
reference age without pre-pending a 'self.'

-Dave
"John Fouhy" <john at fouhy.net> wrote in message
news:5e58f2e40601121516l3075bc6bh at mail.gmail.com...
> On 13/01/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
> > I just read about __init__ in the chapter on operator
> > overloading in Learning Python.  What is __init__
> > exactly?  Is it a special function that you can use to
> > initialize attributes in an object upon creation?
>
> Pretty much ...  Have you read about defining your own classes yet? [I
> don't have Learning Python]
>
> If you haven't, then don't worry about it --- the book will surely
> cover __init__ when you get to defining classes.
>
> But, either way, here is a short example:
>
> >>> class MyClass(object):
> ...  def __init__(self):
> ...   print 'Initialising MyClass instance now...'
> ...   self.x = 3
> ...
> >>> m = MyClass()
> Initialising MyClass instance now...
> >>> m.x
> 3
>
> --
> John.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>





More information about the Tutor mailing list