champ885
champ885

Reputation: 9

Unexpected Result when calling a Class method

Unexpected Result when calling a Class method

HI there I get the following result (<class 'range'>) when I try to call the range variable from the "Battery" Class below:

Result:

This car can go about <class 'range'> miles on a full charge. 2019 Tesla Model S This car has a 75-kwh battery.

Is anyone able to point to the right place to fix this?

see code below:

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()

Please, I am still very new to Python, so would really appreciate your dumbing it down for me.. Thanks.

Upvotes: 1

Views: 100

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51643

In case self.battery_size is neither 75 nor 100, you wont assing anything to range.

"Luckyly" range is already a built in so you do not get a NameError but print its type instead.

Fix:

    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.")

You should never use built in names as variables yourself - you shadow the built in which gives you grief in the long run.

See https://docs.python.org/3/library/functions.html

Upvotes: 0

ForceBru
ForceBru

Reputation: 44838

The name range is a built-in (you use it like for x in range(100):). You overwrite it with an integer (like range = 315) if self.battery_size equals 75 or 100. If none of these conditions is met, range won't be overwritten and will still refer to the built-in class range.

How to solve:

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.")

Upvotes: 2

Related Questions