Object Oriented

Python is an imperative, procedural, functional and object oriented language. As you can see is in fact a hybrid language. That means we can define classes and we can create instances of the classes that are called objects, like in Java. This may be true but the syntax is a lot different.


class Dog:
    kind = "canine" # class variable
    def __init__(self, name):
        self.name = name #instance variable
        self.tricks = [] #instance variable
    def add_trick(self, trick):
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')

print(e.name, e.tricks)
print(d.name, d.tricks)


The __init__  function is the constructor. This has 2 parameters: self and name. When a new object is called from class Dog, only one parameters is required.

Buddy ['roll over']
Fido ['play dead'


Many developers have difficulty to understand difference between a class variable and object variable. Any variable defined in local scope of the class are shared between all objects of the class. All instance variables must use self. prefix and can be initialized in the constructor.


A class can inherit from another class. Observe in the constructor of “Dog” we call the super() this is the super class and __init__ that is the constructor for the parent class. super() is Python 3 syntax. For Python 2 this we could be a call like this: super(Dog, self).__init(“Dog”)

class Animal:
    def __init__(self, kind): 
        self.kind = kind

class Dog(Animal):
    def __init__(self, name):
        self.name   = name
        self.tricks =[]
    def add_trick(self, trick):

See also: Python documentation