Consider the following (silly) 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")
where the purpose of clone
method is to create a new car of the same type but different color.
Obviously since the clone
operation is common among all classes inheriting from CarABC
it should be a method of the base class. However, the method needs to know the child class that has invoked it to return a car of the correct type.
I was wondering if the way I used in the example is correct (and Pythonic) for figuring out the type of the base class that has invoked the method?