通过创建一个实例作为属性,我可以从 Electric Car class 访问 Car class 的任何方法。任何人都可以深入解释这些吗?

By creating an instance as an attribute, I can access to any method of the Car class from Electric Car class. Can anyone explain these in depth?

class Car:
    def range(self):
        pass

class ElectricCar:
    def __init__(self, model):
        self.model = model 
        self.car = Car()  # <--Explain this one!

electric_car = ElectricCar('Tesla')
electric_car.car.range()  # <---Calling method of Car class

通过创建实例作为属性,我可以从 Electric Car class 访问 Car class 的任何方法。任何人都可以深入解释这些吗?

这与您创建 class ElectricCar() 实例的方式相同。但是您正在为另一个 class 中的 class 汽车创建对象。因此 self.car 是 class 汽车的一个实例。 所以为了调用 class Car 中的方法,你必须调用它 self.car.range() - 这里的 self 被称为父 class 的实例(即 electric_car)。因此,您将范围方法称为 electric_car.car.range()