为什么我的班级正在访问另一个未导入的班级?

时间:2019-02-07 01:05:01

标签: python class import module

我在名为car.py的模块中存储了多个类。一类使用另一类。这是代码。

from car import ElectricCar
my_tesla = ElectricCar('tesla', 'model s', 2016)

ElectricCar类使用存储在同一模块中的Battery类,但是未导入Battery。

class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
    def __init__(self, make, model, year):
        """
        Initialize attributes of the parent class.
        Then initialize attributes specific to an electric car.
        """
        super().__init__(make, model, year)
        self.battery = Battery()

这是来自同一模块car.py的父类Car。

class Car():
"""A simple attempt to represent a car."""

def __init__(self, make, model, year):
    """Initialize attributes to describe the car."""
    self.make = make
    self.model = model
    self.year = year
    self.odometer_reading = 0

这是来自同一模块car.py的Battery类。

class Battery():
"""A simple attempt to model a battery for an electric car."""

    def __init__(self, battery_size=70):
        """Initialize the battery's attributes."""
        self.battery_size = battery_size

    def describe_battery(self):
         """Print a statement describing the battery size."""
         print(f"This car has a {self.battery_size}-kwh battery!")

    def get_range(self):
    """Print a statement about the range this battery provides."""
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
            range = 270

        message = f"This car can go approximately {range}"
        message += " mile on a full charge."
        print(message)

    def upgrade_battery(self):
        if self.battery_size == 70:
            self.battery_size = 85

最后是我用来创建和使用对象的代码。

my_tesla = ElectricCar('tesla', 'model s', 2016)
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()

代码工作正常。我的问题是,当我导入ElectricCar时,如何在未专门导入Battery的情况下能够访问Battery类。作为类似的后续问题,当父类也未导入时,super()方法如何能够访问父类?这是python自然运行的方式吗?

0 个答案:

没有答案