从基类中查找实例类型的Pythonic方法是什么?

2024-05-14 23:26:41 发布

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

考虑以下(愚蠢)MWE:

from abc import ABC, abstractmethod

class CarABC(ABC):
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def __str__(self):
        return "%s %s" % (self.color, self.name)

    @abstractmethod
    def run(self):
        raise NotImplementedError()

    def clone(self, color):
        car = type(self)
        return car(color)

class Ford(CarABC):
    def __init__(self, color):
        super().__init__("Ford", color)


    def run(self):
        print("Ford is running")


class Toyota(CarABC):
    def __init__(self, color):
        super().__init__("Toyota", color)

    def run(self):
        print("Toyota is running")

其中clone方法的目的是创建相同类型但不同颜色的新车

显然,由于clone操作在从CarABC继承的所有类中都是通用的,因此它应该是基类的方法。但是,该方法需要知道调用它以返回正确类型的car的子类

我想知道我在示例中使用的方法是否正确(并且是Pythonic的),以确定调用该方法的基类的类型


Tags: 方法runnameself类型cloneinitdef
1条回答
网友
1楼 · 发布于 2024-05-14 23:26:41

根据[Python 3.Docs]: Built-in Functions - class type(object)重点是我的):

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.class.

The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

在这里使用isinstance显然是一个糟糕的设计决策,因为基类必须知道(并迭代)它的所有子类

清洁剂克隆方法变体为:

def clone(self, color):
    cls = self.__class__
    return cls(color)

缺点是,如果向子类初始值设定项添加一些其他(非默认)参数,则无法对其进行实例化

需要注意的是,在这种情况下使用类型可以(如果使用旧式类,这可能是唯一的方法,但是这些类只存在于Python 2中。

相关问题 更多 >

    热门问题