Skip to content

Objects

Defining an Object

class Dog():
    """ A simple class to represent a dog"""

    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.good_boy = True    # setting a default value

    def sit(self):
        pass

my_dog = Dog("Fido", 6)

Notes:

  1. Class names are written in CamelCase
  2. In python2.7 objects are declared as class Dog(object):

Child Classes

class Car():
    def __init__(self, make, model, year):
        <snip>

class ElectricCar(Car):
    def __init__(self, make, model, year):
        super.__init__(make,model,year)
        <snip>

In python 2 this is a little different

class Car(object):
    def __init__(self, make, model, year):
        <snip>

class ElectricCar(Car):
    def __init__(self, make, model, year):
        super(ElectricCar, self).__init__(make,model,year)
        <snip>

Overriding Parent Methods

If a child class defines a method with the same signature as its parent, the child's method will be used.

Importing Classes

from Car import Car, ElectricCar

'Repeated' imports

# file: electric_car.py

from car import Car

class ElectricCar(Car):
    <snip>

# file: my_car.py

from Car import Car
from electric_car import ElectricCar

Python handles the 'repeated' import of Car without any issue.