我正在努力改进Python中的OOP,我在编写的一个程序中遇到了一些真正的黑客行为。行得通,但一团糟。你知道吗
下面是一个简短的测试示例。它将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上安装python2.4.3。谢谢!你知道吗
如果我对你的问题理解正确,你想把汽车清单附在公司对象上:
有更多的清理工作可以做,但我认为这应该解决你眼前的问题。你知道吗
相关问题 更多 >
编程相关推荐