Hello, I want to know and understand how and when do we need to implement classes in our code, I have written a program in python just using functions but never feel the need of using classes, so I was thinking when we can create something without classes why do we need to use them and also what are class constructor and I have learnt from research that ever classes has constructor the how dowe figure out what should we initiate from a constructor....

please help me learn all this....

In a nutshell, a class combines methods/functions that belong together.

A typical class example ...

'''Class_Animal1.py
a look at a simple Python class

a class combines methods/functions that belong together
to keep methods private, prefix with a double underline only

see also:
http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
tested with python27, python32, python33
'''

class Animal():
    """
    class names by convention are capitalized
    """
    def __init__(self, animal, sound):
        """
        __init__() is the 'constructor' of the class instance
        when you create an instance of Animal you have to supply
        it with the name and the sound of the animal
        'self' refers to the instance
        if the instance is dog, then
        name and 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):
        """
        the first argument of a class method is always self
        this method needs to be called with self.speak() within
        the class, or the instance_name.speak() outside the class
        """
        print( "The %s goes %s" % (self.name, self.sound) )


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

# now you can call each animal's function/method speak()
# by simply connecting instance_name and speak() with a '.'
cow.speak()
cat.speak()
dog.speak()

# you can also access variables associated with the instance
# since cow is the instance
# self.sound becomes cow.sound
print(cow.sound)

As you can see a class can be reused through its instances many different ways. A class can also inherit another class and used the methods of that class and so on.

Edited 4 Years Ago by vegaseat

what are the guiding principles of Python? the link on that page doesnt work !!!

This article has been dead for over six months. Start a new discussion instead.