我有一个基类的实例,然后我想使它成为此基类的子类的实例。也许我以一种错误的方式解决问题,在OOP中有一些重要的东西我不明白。代码只是为了说明,并且可以提出一种非常不同的方法。任何帮助赞赏。继承:将基类实例转换为子类实例
class Car(object):
def __init__(self, color):
self.color = color
def drive(self):
print "Driving at 50 mph"
class FastCar(Car):
def __init__(self, color, max_speed=100):
Car.__init__(self, color)
self.max_speed = max_speed
def drive_fast(self):
print "Driving at %s mph" %self.max_speed
one_car = Car('blue')
# After the instanciation, I discovered that one_car is not just a classic car
# but also a fast one which can drive at 120 mph.
# So I want to make one_car a FastCar instance.
我看到一个非常类似的问题,但没有答案的适合我的问题:
我不想让FastCar围绕汽车的包装,其知道如何开快车:我真的希望FastCar扩展Car;
我真的不希望使用FastCar的
__new__
方法做出的论点一些测试,并决定是否__new__
必须返回车的新实例或者我给它的实例(例如:def __new__(cls, color, max_speed=100, baseclassinstance=None)
)。
为什么你不这样做:one_car = FastCar(one_car.color,120)?这不是真正的继承或什么,但应该工作。 – Bogdan
您的OOP设计看起来有点不合适。我会想象FastCar也会实现drive(),但是会以更高的速度执行(你已经实现了drive_fast)。用你现在拥有的东西,调用者必须知道类型以知道调用哪个方法(坏),而不是调用相同的方法,并让各种类型适当地实现该方法(良好)。您也可以通过在FastCar类的末尾添加'drive = drive_fast'来完成此操作。 – PaulMcG
好的。一个更好的例子:'FastCar'没有'drive_fast'方法,但是'overtake'方法不存在'Car'。 – Andy