基于“类变量”列表引擎大小中可用的值,关于该方法需要做什么的任何提示都将增加我所拥有的引擎大小变量?
例如如果将self.engine设置为1.6,如何检查类变量列表engine_sizes并找到下一个最大的引擎大小并将其设置为该大小。
下面是我到目前为止的代码:
class Car(object):
engine_sizes = [1.1, 1.6, 1.8, 1.9]
def __init__(self, make, model, engine):
if engine not in self.engine_sizes:
raise ValueError("%s is not a valid engine size." % engine)
self.__make = make
self.__model = model
self.style = style
self.engine = engine
def increase(self):
if self.engine == max(self.engine_sizes):
print("Engine is too big to increase")
else:
self.engine = next(self.engine_sizes )
print("Engine Size Updated")
答案 0 :(得分:1)
最快的解决方法是而不是
self.engine = next(self.engine_sizes )
尝试
self.engine = Car.engine_sizes[Car.engine_sizes.index(self.engine) + 1]
通常,最好将引擎的索引存储在类中,并提供@property
以获取引擎大小。如果您有许多引擎尺寸,这样做会更有效率。不过,对于四个,上面的修复应该没问题。
答案 1 :(得分:0)
由于一些原因,您无法以编写代码的方式执行此操作。一种是,如果将engine_sizes
设为类变量,则该类的所有实例将共享对同一对象的引用。但更重要的是,因为list
对象是可迭代的,但它们不是迭代器。
您可以尝试这样的事情:
class Car(object):
engine_sizes = [1.1, 1.6, 1.8, 1.9]
def __init__(self, make, model, engine):
if engine not in self.engine_sizes:
raise ValueError("%s is not a valid engine size." % engine)
self.__make = make
self.__model = model
self.style = style
self.engine = engine
def increase(self):
if self.engine == max(self.engine_sizes):
print("Engine is too big to increase")
else:
idx = self.engine_sizes.index(self.engine)
self.engine = self.engine_sizes[idx + 1]
print("Engine Size Updated")