pythonclasstry-except

Beginner Classes - Calling a variable name in a function and if I used a try/except properly


I just started learning Python/coding in general. I tried to find an answer to this but couldn't. So I created this code for a Class "Vehicle" in my lab:

class Vehicle(object):
    def __init__(self, maxspeed, mileage, color="white"):
        self.maxspeed=maxspeed;
        self.mileage=mileage;
        self.color=color;
        
    def assign_seating_capacity(self, seating_capacity):
        self.seating_capacity=seating_capacity
        
    def properties(self):
        print("Properties of the vehicle:")
        print("Maximum Speed:", self.maxspeed)
        print("Mileage:", self.mileage)
        print("Color:", self.color)
        try:
            print("Seating Capacity:", self.seating_capacity) 
        except AttributeError:
            print("Seating capacity unknown")

And then I created a few objects, "vehicle1", vehicle2" and so forth. My first question: is there a way to call a variable name in the function "properties"? So instead of saying "Properties of the vehicle:" it would say "Properties of vehicle1:"? Or is that way too complicated?

My second question is did I use the try/except properly? I thought I was so clever with how I got around the error that happened if I used the "properties" method without first using the "assign_seat_capacity" one. But in my lab they just did it like this:

class Vehicle:
    color = "white"

    def __init__(self, max_speed, mileage):
        self.max_speed = max_speed
        self.mileage = mileage
        self.seating_capacity = None

Is it smarter to do it this way or does it not really matter? Thank you in advance for reading all of this! <3

I had no idea what to do but I tried print("Properties of", self, ":") and name, self.name, variable - even though I knew they wouldn't work


Solution

  • If you maintain your Vehicle instances in a list then you effectively get what you want. Rather than having a distinct variable for each Vehicle instance it's just an offset into a list.

    For example:

    class Vehicle:
        _id = -1
        def __init__(self, maxspeed: int, mileage: int, colour: str='white', seating_capacity: int|None=None):
            self.maxspeed = maxspeed
            self.mileage = mileage
            self.colour = colour
            self._seating_capacity = seating_capacity
            Vehicle._id += 1
            self._id = Vehicle._id
        @property
        def seating_capacity(self) -> str|int:
            return 'Unknown' if self._seating_capacity is None else self._seating_capacity
        @seating_capacity.setter
        def seating_capacity(self, value: int):
            self._seating_capacity = value
        def __str__(self):
            return f'ID: {self._id}\nMax speed: {self.maxspeed}\nMileage: {self.mileage:,}\nColour: {self.colour}\nSeating capacity: {self.seating_capacity}\n'
    
    vehicles: list[Vehicle] = []
    
    vehicles.append(Vehicle(150, 1))
    vehicles.append(Vehicle(120, 15000, 'blue', 4))
    
    print(*vehicles, sep='\n')
    
    vehicles[0].seating_capacity = 5
    vehicles[1].maxspeed = 145
    
    print('---Data changed---')
    print(*vehicles, sep='\n')
    

    Output:

    ID: 0
    Max speed: 150
    Mileage: 1
    Colour: white
    Seating capacity: Unknown
    
    ID: 1
    Max speed: 120
    Mileage: 15,000
    Colour: blue
    Seating capacity: 4
    
    ---Data changed---
    ID: 0
    Max speed: 150
    Mileage: 1
    Colour: white
    Seating capacity: 5
    
    ID: 1
    Max speed: 145
    Mileage: 15,000
    Colour: blue
    Seating capacity: 4