I’m working on getting better with OOP in Python and I’ve run into some real hackishness in one program I’m writing. It works, but it’s a mess.
Below is a short test example to illustrate. It creates cars of either 0, 2, or 4 windows into a list, and then compares the first element with the rest of the list.
The 3rd method of the first class shows what I’m worried about. I just want to be able to refer to whatever container that particular object is in without having to call it from the parameters each time. It isn’t even that bad in this example, but what I’m working on has it in so many places that it’s starting to get confusing.
import random
class Car:
def __init__ (self, company, doors, id):
self.company = company
self.doors = doors
self.id = id
def printDoors(self, id):
print 'Car ' + `self.id` + ' has ' + `self.doors` + ' doors.'
def findSameDoors(self, id):
# these next lines are the ones that really bother me
companyAbstract = self.company + 's'
for i in eval(companyAbstract):
if self.id != i.id and self.doors == i.doors:
print 'Car ' + `i.id` + ' does too!'
class Company:
def __init__ (self, types):
self.types = types
def typesToNum(self):
result = []
for i in self.types:
if i == 'sedan':
result.append(4)
elif i == 'convertible':
result.append(2)
else:
result.append(0)
return result
porsche = Company(['sedan', 'convertible'])
honda = Company(['sedan', 'convertible', 'motorcycle'])
porsches = []
for i in range(10):
porsches.append(Car('porsche', random.choice(porsche.typesToNum()), i))
hondas = []
for i in range(10):
hondas.append(Car('honda', random.choice(honda.typesToNum()), i))
porsches[0].printDoors(0)
porsches[0].findSameDoors(0)
Just in case it matters, Python 2.4.3 on RHEL. Thanks!
If I’m understanding your question right, you want to attach the list of cars to the company object:
There’s more cleanup that could be done to it, but I think that should solve your immediate concern.