从基类创建派生类,然后在Python程序中使用派生类。该程序应创建两个摩托车对象,然后设置摩托车的速度,加速摩托车对象,并检查其边车状态。 必须使用此类来运行以下类:
class Motorcycle:
maxspeed = 0
minspeed = 0
sidecar = ""
def __init__(self, maxspeed, minspeed, sidecar):
self.maxspeed = maxspeed
self.minspeed = minspeed
self.sidecar = sidecar
def sidecar(self):
self.get_sidecar = True
return self.get_sidecar
def speed(self, speed):
self.speed = self.minspeed + self.accelerate
return self.speed
def accelerate(self, accelerate):
self.accelerate = accelerate
if (self.accelerate + self.minspeed) > self.maxspeed:
print("This motorcycle cannot go that fast")
课后:
from Motorcycle import Motorcycle
motorcycleOne = Motorcycle(90.0, 65.0, True)
motorcycleTwo = Motorcycle(85.0, 60.0, False)
motorcycleOne.accelerate(30.0)
motorcycleTwo.accelerate(20.0)
print("The current speed of motorcycleOne is " + str(motorcycleOne.speed))
print("The current speed of motorcycleTwo is " + str(motorcycleTwo.speed))
if motorcycleOne.sidecar:
print("This motorcycle has a sidecar")
else:
print("This motorcycle does not have a sidecar")
if motorcycleTwo.sidecar:
print("This motorcycle has a sidecar")
else:
print("This motorcycle does not have a sidecar")
我一直收到这条消息来检索速度:绑定方法...... 我不知道从哪里可以找到任何建议我会非常感激。
答案 0 :(得分:0)
speed
和sidecar
都是方法;你需要打电话给他们。
print("The current speed of motorcycleOne is " + motorcycleOne.speed())
注意,您似乎没有按照说明创建基类和派生类。
答案 1 :(得分:0)
您正在混合属性和方法。 您的“速度”应该是您班级的属性,而“加速”应该是修改该属性的方法。 一些代码显示我的意思。
class Motorcycle:
def __init__(self, maxspeed, minspeed, sidecar):
self.maxspeed = maxspeed
self.minspeed = minspeed
self.speed = minspeed # Initial speed is equal to minspeed
self.sidecar = sidecar
# Printing methods
# Print sidecar status
def has_sidecar(self):
if self.sidecar:
print("This motorcycle has a sidecar")
else:
print("This motorcycle does not have a sidecar")
# Print speed
def how_fast(self):
print ("The current speed of this motorcycle is {}".format(self.speed))
# Methods to change your sidecar status:
def add_sidecar(self):
self.sidecar = True
def remove_sidecar(self):
self.sidecar = False
# Method to accelerate
def accelerate(self, accelerate):
if (self.speed + accelerate) > self.maxspeed:
print("This motorcycle cannot go that fast")
else:
self.speed += accelerate
motorcycleOne = Motorcycle(90.0, 65.0, True)
motorcycleTwo = Motorcycle(85.0, 60.0, False)
motorcycleOne.accelerate(30.0)
motorcycleTwo.accelerate(20.0)
motorcycleOne.how_fast()
motorcycleTwo.how_fast()
motorcycleOne.has_sidecar()
motorcycleTwo.has_sidecar()
给出:
This motorcycle cannot go that fast
The current speed of this motorcycle is 65.0
The current speed of this motorcycle is 80.0
This motorcycle has a sidecar
This motorcycle does not have a sidecar
...
但是你不是从基类中继承类。