gpt4 book ai didi

python - 继承 : transform a base class instance to a child class instance

转载 作者:行者123 更新时间:2023-12-01 15:34:01 24 4
gpt4 key购买 nike

我有一个基类的实例,然后我想让它成为这个基类的子类的实例。也许我以错误的方式解决了这个问题,并且在 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 成为知道如何快速行驶的 Car 的包装器:我真的希望 FastCar 扩展 Car ;

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

最佳答案

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)

这是标准方式。

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

classic = Car('blue')

classic.__class__ = FastCar
classic.__dict__.update(FastCar(classic.color).__dict__)

classic.drive_fast()

但我不推荐它——这是一种 hack,它并不总是有效,而另一种方法更干净。

编辑: 基本上是要添加@PaulMcGuire 的评论所说的内容。听从这个建议,他是对的。

关于python - 继承 : transform a base class instance to a child class instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7078134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com