我正在努力在Python中使用OOP变得更好,并且我在一个正在编写的程序中遇到了一些真正的hackishness。它有效,但它是一团糟。
下面是一个简短的测试示例来说明。它会将0,2或4个窗口的汽车创建到列表中,然后将第一个元素与列表的其余部分进行比较。
第一节课的第三种方法显示了我所担心的问题。我只是希望能够引用特定对象所在的任何容器,而无需每次都从参数中调用它。在这个例子中它甚至不是那么糟糕,但是我正在研究的是它在很多地方都有它开始变得混乱。
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)
以防万一,RHEL上的Python 2.4.3。谢谢!
答案 0 :(得分:3)
如果我正确理解您的问题,您需要将汽车列表附加到公司对象:
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):
for i in self.company.cars:
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
self.cars = []
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'])
for i in range(10):
porsche.cars.append(Car(porsche, random.choice(porsche.typesToNum()), i))
for i in range(10):
honda.cars.append(Car(honda, random.choice(honda.typesToNum()), i))
porsche.cars[0].printDoors(0)
porsche.cars[0].findSameDoors(0)
可以对它进行更多清理,但我认为这应该可以解决您的直接问题。