继承:将基类实例转换为子类实例

2024-10-01 17:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基类的实例,然后我想让它成为这个基类的子类的实例。也许我把问题搞错了,在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扩展汽车;

  • 我真的不想使用FastCar中的__new__方法对参数进行一些测试,并决定__new__是否必须返回Car的新实例或我给它的实例(例如:def __new__(cls, color, max_speed=100, baseclassinstance=None))。


Tags: 实例selfnewinitdefdrivecarone
3条回答

可以借用C++复制概念的“复制构造函数”来做这样的事情。在

允许Car的构造函数获取Car实例,并复制其所有属性。然后FastCar应该接受Car实例或FastCar实例。在

所以,要转换汽车,只需做one_car = FastCar(one_car)。请注意,这不会影响对原始汽车对象的引用,原始汽车对象仍将指向同一辆汽车。在

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

    @staticmethod
    def fromOtherCar(car):
        return FastCar(car.color)

actually_fast = FastCar.fromOtherCar(thought_was_classic)

这是标准方法。在

根据实际的类布局,您可以执行以下操作:

^{pr2}$

但我不推荐它——这是一种黑客攻击,它并不总是有效的,另外一种方法更干净。在

编辑:只是想补充一下@PaulMcGuire的评论。听他的建议,他是对的。在

为什么不只用一门课呢?在

class Car(object):
    def __init__(self, color, max_speed = 50):
        self.color = color
        self.max_speed = max_speed
    def drive(self):
        print "Driving at %s mph"%self.max_speed

c=Car('blue')
c.max_speed = 100

相关问题 更多 >

    热门问题