我有一个基类的实例,然后我想把它变成这个基类的子类的实例。也许我在解决问题的方式上有误,并且在面向对象编程中有一些重要的东西我没有理解。代码只是为了说明,可以建议非常不同的方法。任何帮助都将不胜感激。
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成为一个包装Car的东西,它知道如何快速驾驶:我真的希望FastCar扩展Car;
我不想在FastCar中使用
__new__
方法对参数进行测试,并决定__new__
是否必须返回Car的新实例或我给它的实例(例如:def __new__(cls, color, max_speed=100, baseclassinstance=None)
)。
FastCar
没有drive_fast
方法,但有一个overtake
方法,这个方法对于Car
是不存在的。 - AndyCar
来自外部模块,并且color
实际上是Car
的私有成员__color
。或者Car.__init__
不仅将color
分配给self.color
,而且对颜色进行了大量计算(实际上是一个大的numpy.array
),而我不能重复这些计算来创建FastCar
。 - Andy__new__
或__init__
。但是,如果您认为需要这样做,则可能需要重新设计您的继承/类结构。 - agf