1

I started learning python (with no prior knowledge of it, not programming) few weeks ago and am stuck at Classes. Currently the "init" class method confuses me. What does it do, in fact?

Here is an example of the init method usage I am copying from particular python book:

class Person:
    def __init__(self, name):
       self.name = name

    def sayHi(self):
       print "Hello, my name is", self.name

p = Person("George")
p.sayHi()

Please do correct me, but the same result could be achieved without the _init method, like so:

class Person:
    def sayHi(self, name):
       print "Hello, my name is", name

p = Person()
p.sayHi("George")

Right?

So what is the purpose of the init method anyway?

Thank you.

stgeorge
  • 483
  • 3
  • 7
  • 16
  • 2
    Of course you *could* do it that way, but then there's no purpose in having a class at all -- you could just `def sayHi(name):...` -- The purpose of a class is to group data (attributes like `name`,`age`,...) along with methods (functions) to work with the data. Your `Person` class could have an `age` attribute and a `have_birthday` method which incremented the age for example. – mgilson Jun 06 '13 at 12:34
  • Thank you for the reply mgilson. In the book I am reading (A byte of python), fields and methods are subcategories of attributes. It seems you are saying opposite? "_Collectively, the fields and methods can be referred to as the attributes of that class._" – stgeorge Jun 06 '13 at 14:31

1 Answers1

3
__init__

in python is similar to constructor in c++ or java.

limovala
  • 459
  • 1
  • 5
  • 16