python - 在 Python 中创建基类返回子对象

标签 python oop

我有一个包含两个子类的基类,比如 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/

相关文章:

java - 关于Java中父类(super class)变量引用子类对象

python - Django 数据库设置 'Improperly Configured' 错误

python - 使用 Python 发送 MIDI 消息(在 Ubuntu 上)

python - Psycopg2 问题将值插入数据库中的现有表

programming-languages - 为什么smalltalk不是一种功能编程语言?

php - 使用范围解析运算符 (::) 将常量传递给 PHP 方法的最佳方法

python - TypeError : must be string without null bytes, 不是 str

python - 如果特定列中的值不是 pandas 数据框中的整数,则删除行

java - 面向对象 : new class implementing requires additional parameter

c# - C#中如何调用接口(interface)