Python 调用类方法时出现意外结果

Python 调用类方法时出现意外结果,python,Python,调用类方法时出现意外结果 您好,当我尝试从下面的“Battery”类调用range变量时,我得到了以下结果() 结果: 这辆汽车充满电后可以行驶约英里。 2019特斯拉S型 这辆车有75千瓦时的电池 有人能指出正确的地方来解决这个问题吗 见下面的代码: class Car: """A simple attempt to represent a car. """ def __init__(self, make, mode

调用类方法时出现意外结果

您好,当我尝试从下面的“Battery”类调用range变量时,我得到了以下结果()

结果:

这辆汽车充满电后可以行驶约英里。 2019特斯拉S型 这辆车有75千瓦时的电池

有人能指出正确的地方来解决这个问题吗

见下面的代码:

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

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

    def get_descriptive_name(self):
        """Return a neatly formatted descriptive name."""
        long_name =f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self):
        """Print a statement showing the car's mileage."""
        print(f"This car has {self.odometer_reading} miles on it. ")

    def update_odometer(self, mileage):
        """Set the odometer reading to the given value."""
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        """Add the given amount to the odometer reading."""
        self.odometer_reading += miles
    #moving battery attributes from electric cars to  a separate class for
class Battery:
        def __init__(self, battery_size=75):
             """Print a statement describing the battery size."""
             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 == 75:
                    range = 260
                elif self.battery_size == 100:
                    range = 315

        print(f"This car can go about {range} miles on a full charge.")

#Electric car subclass
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 the attributes of the parent class"""
            super().__init__(make, model, year)
            self.battery = Battery()

# for electric cars
my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

print("\n")

# Car 1
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()

print("\n")

# car 2
my_new_car01 = Car("toyota", 'corrolla', 2024)
print(my_new_car01.get_descriptive_name())
my_new_car01.odometer_reading = 23
my_new_car01.read_odometer()
print("\n")

# Car 3
my_new_car03  = Car("Benz", 'AMG', 2021)
print(my_new_car03.get_descriptive_name())

# update odometer
my_new_car03.update_odometer(23)
my_new_car03.read_odometer()

#Used car
my_used_car = Car('subaru', 'outback', 2015)
print(my_used_car.get_descriptive_name())

# Update odometer
my_used_car.update_odometer(23500)
my_used_car.read_odometer()

#Increment Odometer
my_used_car.increment_odometer(100)
my_used_car.read_odometer()

拜托,我对Python还是很陌生,所以非常感谢你帮我简化一下。。谢谢。

名称
range
是内置的(您可以像
一样使用它来表示range(100)中的x:
)。如果
self.battery\u size
等于75或100,则用整数覆盖它(如
range=315
)。如果这些条件都不满足,
范围
将不会被覆盖,并且仍将引用内置类
范围

如何解决:

miles = 'unknown'
if self.battery_size == 75:
    miles = 260
elif self.battery_size == 100:
    miles = 315

print(f"This car can go about {miles} miles on a full charge.")

如果
self.battery\u size
既不是75也不是100,则您不会将任何内容分配到
范围

“Luckyly”
range
已经是内置的,因此您不会得到
namererror
,而是打印它的类型

修正:

你不应该自己使用内置的名字作为变量——你会给你带来长期痛苦的内置名字蒙上阴影


请参阅您的
打印(f“这辆车在充满电的情况下可以行驶大约{range}英里)。
没有正确缩进,因此它不在
get\u range
方法内。谢谢。。非常感谢@khelwoodThank非常感谢..正如一位撰稿人所指出的,if语句似乎也存在缩进问题。。再次感谢
    def get_range(self): 
        """Print a statement about the range this battery provides.""" 

        b_range = "unknown"
        if self.battery_size == 75:
            b_range = 260
        elif self.battery_size == 100:
            b_range = 315

        print(f"This car can go about {b_range} miles on a full charge.")