Skip to content

Instantly share code, notes, and snippets.

@dbarnett
Created February 11, 2012 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbarnett/1797426 to your computer and use it in GitHub Desktop.
Save dbarnett/1797426 to your computer and use it in GitHub Desktop.
Object-oriented demonstration for SO question http://stackoverflow.com/q/9237725/307705
import random
class Vehicle(object):
def __init__ (self, _id):
self.company = None
self.id = _id
def printDoors(self):
print 'Car ' + str(self.id) + ' has ' + str(self.doors) + ' doors.'
def findSameDoors(self):
for i in self.company.cars:
if self.id != i.id and self.doors == i.doors:
print 'Car ' + str(i.id) + ' does too!'
class Sedan(Vehicle):
name = 'sedan'
doors = 4
class Convertible(Vehicle):
name = 'convertible'
doors = 2
class Motorcycle(Vehicle):
name = 'motorcycle'
doors = 0
class Company(object):
def __init__ (self, name, types):
self.name = name
self.types = types
self.cars = []
def add_vehicle(self, vehicle):
self.cars.append(vehicle)
vehicle.company = self
porsche = Company('Porsche', [Sedan, Convertible])
honda = Company('Honda', [Sedan, Convertible, Motorcycle])
for i in range(10):
vehicle_class = random.choice(porsche.types)
porsche.add_vehicle(vehicle_class(i))
for i in range(10):
vehicle_class = random.choice(honda.types)
honda.add_vehicle(vehicle_class(i))
porsche.cars[0].printDoors()
porsche.cars[0].findSameDoors()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment