我有一个包含两个子类的基类,比如 Car 包含子类 HeavyCar 和 LightCar。是否可以让基类的创建返回依赖于变量的子类的对象?像这样:
weightA = 2000
myAcar = Car(weigthA) # myAcar is now of type HeavyCar
weightB = 500
myBcar = Car(weightB) # myBcar is now of type LightCar
我知道执行此操作的正常方法是查看权重变量,然后决定我想要什么类型的对象,然后创建该特定对象。但是,我想由我的类(class)来决定它应该是哪种类型,而不必在类(class)之外为它烦恼,即根本不必查看可变重量。
最佳答案
您可以覆盖 __new__
以使其返回所需的类型。但是,定义一个执行相同操作的函数会更简单,因为它不太容易出错。
使用 __new__
class Car(object):
def __init__(self, weight):
self.weight = weight
def __new__(cls, weight):
if cls is Car:
if weight > 1000:
return object.__new__(HeavyCar)
else:
return object.__new__(LightCar)
else:
return object.__new__(cls)
class LightCar(Car):
def __init__(self, weight):
super(LightCar, self).__init__(weight)
self.speed = "fast"
class HeavyCar(Car):
pass
assert isinstance(Car(10), LightCar)
assert Car(10).weight == 10 # Car.__init__ invoked
assert hasattr(Car(10), "speed") # LightCar.__init__ invoked as well
assert isinstance(Car(1001), HeavyCar)
assert Car(1001).weight == 1001 # Car.__init__ invoked
使用函数
def create_car(weight):
if weight > 1000:
return HeavyCar(weight)
else:
return LightCar(weight)
assert isinstance(create_car(10), LightCar)
关于python - 在 Python 中创建基类返回子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29301796/