首页 > 编程语言 > 详细

在python中编写一个简单的关于类的情况遇到的问题(待解决)

时间:2020-01-13 21:48:25      阅读:96      评论:0      收藏:0      [点我收藏+]

在编写一个关于类的问题时,在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?

在python中编写一个简单的关于类的情况遇到的问题(待解决)

原文:https://www.cnblogs.com/lijitao/p/12189026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!