<p>在我看来,您所需要的只是一个函数,它接受<code>carMake</code>、<code>carModel</code>、<code>carType</code>等,然后包含所有这些<code>if</code>语句。如果您想输入有关汽车的所有数据,然后用相同的数据调用多个不同的函数,那么类将非常有用。你知道吗</p>
<p>下面是如何使用函数:</p>
<pre><code>def calcInsurance (make, model, type, engineSize, yearsClaimFree, startingRate):
if engineSize >= 2.0:
startingRate = startingRate * 2.5
elif engineSize >= 1.4:
startingRate = startingRate * 1.5
else:
print("Engine size is not effecting car insurance quote.")
if carType == "sport":
startingRate = startingRate + 400
else:
print("Car type is not effecting the car insurance quote.")
if yearsClaimFree >= 10:
startingRate = startingRate - startingRate / 5
else:
print("No discount gained from years claimed free.")
print("Your car insurance is €" + str(startingRate))
</code></pre>
<p>现在,如果您希望有更多的函数使用关于同一辆车的相同数据(<code>make</code>、<code>model</code>、<code>type</code>、<code>engineSize</code>、<code>yearsClaimFree</code>和<code>startingRate</code>),那么类可能很有用。你知道吗</p>
<pre><code>class Car:
def __init__ (self, make, model, type, engineSize, yearsClaimFree, startingRate):
self.make = make
self.model = model
# etc.
def calcInsurance (self):
# this function is exactly the same as I showed you before, except each of the car variables need to be preceded with self.
car = Car(...car_data...)
car.calcInsurance()
</code></pre>
<p>如果你有更多的功能,你想做的汽车,你可以调用他们与相同的数据,这辆车只是通过使用</p>
<pre><code>car.calcInsurance()
car.doSomethingElse()
</code></pre>
<p>这就是使用类派上用场的地方。你知道吗</p>