在编写一个关于类的问题时, 在 car 文件中有关于汽车和电动车的描述, 还有一些输出语句. 当我把汽车这个类引入另外一个文件时, 发现整个文件都被执行了.
源代码如下:
car.py
- class Car():
- def __init__(self, make, model, year):
- self.make = make
- self.model = model
- self.year = year
- self.odometer_reading = 0
- def get_descriptive_name(self):
- long_name = str(self.year) + '' + self.make +' ' + self.model
- return long_name.title()
- def read_odometer(self):
- print("This car has" + str(self.odometer_reading) + "miles on it")
- def update_odometer(self, mileage):
- if mileage>= self.odometer_reading:
- self.odometer_reading = mileage
- else:
- print("You can not roll back an odometer!")
- def increment_odometer(self, miles):
- self.odometer_reading += miles
- class Battry():
- def __init__(self, battery_size = 70):
- self.battery_size = battery_size
- def describe_battery(self):
- print("This car has a" + str(self.battery_size) + "-kWH battery.")
- def get_range(self):
- if self.battery_size == 70:
- range = 240
- elif self.battery_size == 85:
- range = 999
- message = "This car go approximately" + str(range)
- message += "miles on a full charge."
- print(message)
- class ElectircCar(Car):
- def __init__(self, make, model, year):
- super().__init__(make, model, year)
- self.battery =Battry()
- my_tesla = ElectircCar('tesla','model s',2016)
- print(my_tesla.get_descriptive_name())
- my_tesla.battery.describe_battery()
- my_tesla.battery.get_range()
- print("i am just for a test")
当我只想引用上边文件中汽车这个类时, 发生了意向不到的情况.
my_car.py
- from car import Car
- my_new_car = Car('audi','a4',2016)
- print(my_new_car.get_descriptive_name())
- my_new_car.odometer_reading = 23
- my_new_car.read_odometer()
输出:
2016 Tesla Model S
This car has a 70-kWH battery.
This car go approximately 240 miles on a full charge.
- i am just for a test
- 2016 Audi A4
- This car has 23 miles on it
从输出语句中可以发现, car.py 整个文件都被执行了, 而我在 my_car.py 中声明的是只引入 Car 这个类, 具体原因还没有想清楚, 等待解决.
将 car.py 中的输出语句注释掉, 就不会有多余的输出语句.
why?
来源: http://www.bubuko.com/infodetail-3379247.html