I need help understanding classes better.

class person:
	def sayHi(self):
		print('hello world!')
p=person()
p.sayHi()

here what is the use of 'self'?, I've read two tuts on this but don't quite understand fully....

class person:
	def _init_(self, name):
		self.name=name
	def sayHi(self):
		print('hello, my name is', self.name)

p=person('rs')
p.sayHi()

And why is _init_ method so special?.
and what are they referring to when they've written 'self.name?'. how does the whole thing above work im at lost completely :-/ .

Under this heading also the author as repeatedly used things like

print('(Initializing {0})'.format(self.name))
print('{0} was the last one.'.format(self.name))

what the heck does {0} do???

could someone please explain this in away a newb can understand:-/

-thank you.

It is easiest to explain __init__() and self with an example ...

# a look at a simple Python class

class Animal(object):
    # this is the constructor of the class
    # when you create an instance you have to supply
    # it with the name and the sound of the animal
    def __init__(self, animal, sound):
        # self refers to the instance
        # if the instance is dog, then
        # the sound will be that of the dog
        # self also makes name and sound available
        # to all the methods within the class
        self.name = animal
        self.sound = sound
        
    def speak(self):
        # a methods arguments always start with self
        print( "The %s goes %s" % (self.name, self.sound) )


# create a few class instances
# remember to supply the name and the sound of the animal
dog = Animal("dog", "woof")
cat = Animal("cat", "meeouw")
cow = Animal("cow", "mooh")

cow.speak()
cat.speak()
dog.speak()

# since cow is the instance
# self.sound becomes cow.sound
print(cow.sound)

Take this example:
you have class of pets and each have method/attribute. See how self applies. Not very neat (one can make it more tidy and neat) but gives idea.

class Dogs():
    def __init__(self)
    
    def OnBarking(self, voice):
        #make voice be attribute/belong of self which is now Dogs class
        self.voice = voice
        self.voice = "baah, baah"
        print "Dog cries wuh! wuh! Wuh!"

class Cats():
    def __init__(self)
    
    def OnMeowing(self, voice):
        #make voice be attribute/belong of self which is now cat class
        self.voice = voice
        self.voice = "Meeh Meeh Meeh"
        print "Cat cries Nyaau! Nyaau! Nyaau!"

It is easiest to explain __init__() and self with an example ...

# a look at a simple Python class

class Animal(object):
    # this is the constructor of the class
    # when you create an instance you have to supply
    # it with the name and the sound of the animal
    def __init__(self, animal, sound):
        # self refers to the instance
        # if the instance is dog, then
        # the sound will be that of the dog
        # self also makes name and sound available
        # to all the methods within the class
        self.name = animal
        self.sound = sound
        
    def speak(self):
        # a methods arguments always start with self
        print( "The %s goes %s" % (self.name, self.sound) )


# create a few class instances
# remember to supply the name and the sound of the animal
dog = Animal("dog", "woof")
cat = Animal("cat", "meeouw")
cow = Animal("cow", "mooh")

cow.speak()
cat.speak()
dog.speak()

# since cow is the instance
# self.sound becomes cow.sound
print(cow.sound)

Thanks for the replies vega and nice sound effects there evstevmd:D,

Anyway, i cant run your script vega??, but now i do understand a tad. Please correct me wherever i am wrong.

So, _init_(self):

is basically the main method like thing which helps run and organize other methods within the class?. It doesnt "do" or return anything but sets a base for methods that come under that class.
(keep in mind of the newbness please:D ).

Also im assuming that in line 18

print( "The %s goes %s" % (self.name, self.sound) )

the %s refers to self.name and self.sound in order.
-----

What is the difference in line 33 and 27?

-thanks alot.

The __init__ function is going to be run automatically whenever you create an instance of a class. It is the setup of your class instance. For example, if your class was a cat, this is where you could set the default age and name of your cat if none was specified. I didn't see anyone mention that __init__ always runs when you create an instance of a class. Take this code for example:

class DoesNothing():
    def __init__(self):
        print 'I have been initialized'

kevin = DoesNothing()

This should print out 'I have been initialized.'

Now I will admit that I'm not super strong on the whole self thing. I do know that self refers to the specific instance of the class you're working on. Check out this class:

class Cat():
    def __init__(self, name="boots", age=5):
        self.name = name
        self.age = age 
    def SayName(self):
        return self.name
    def SayAge(self):
        return self.age

amos = Cat("amos")
able = Cat("Able",3)
default = Cat()

print 'DEFAULT:', default.SayName(), default.SayAge()
print 'AMOS:', amos.SayName(), amos.SayAge()
print 'ABLE:', able.SayName(), able.SayAge()

In each of the three cats that I built, I was able to use the self variable to refer to the name and age of that specific cat. The other thing to note is that when you call functions, python automatically sends the self variable to the function. If you were to remove the (self) from SayAge for example, the code would fail and tell you that an extra argument was sent to the function.

Does that help?

Without the __init__() class constructor this class would behave strange:

class DoesNothing():
    print 'I have been initialized'
This question has already been answered. Start a new discussion instead.