__init__ explanation please

A.T.Hofkamp hat at se-162.se.wtb.tue.nl
Mon Jan 14 03:01:42 EST 2008


On 2008-01-13, Erik Lind <elind at spamcop.net> wrote:
> I'm new to Python, and OOP. I've read most of Mark Lutz's book and more 
> online and can write simple modules, but I still don't get when __init__ 
> needs to be used as opposed to creating a class instance by assignment. For 
> some strange reason the literature seems to take this for granted. I'd 
> appreciate any pointers or links that can help clarify this.

I think you mean the following:
You'd like to do

p = Person('me', 'here', 31)

and you are wondering why you need the __init__() function in

class Person(object):
    def __init__(self, name, addres, age):
        self.name = name
        self.address = address
        self.age = age

right?

If so, the answer is that while you think you are doing "Person('me', 'here', 31)",
you are in reality executing "Person.__init__(self, 'me', 'here', 31)", where
'self' is refers to a shiny new, empty object created for you.

(and the 'self' is obtained by the Person.__new__ function I think, but others
here have much better knowledge about this).


Sincerely,
Albert



More information about the Python-list mailing list