Beginner Classes – Calling a variable name in a function and if I used a try/except properly
Question:
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
Answers:
class Vehicle(object):
def __init__(self, maxspeed, mileage, color="white", seating_capacity=0):
self.maxspeed = maxspeed
self.mileage = mileage
self.color = color
self.seating_capacity = seating_capacity
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)
print("Seating Capacity:", self.seating_capacity)
def __repr__(self):
return f"""
Properties of the vehicle:
Maximum Speed {self.maxspeed}
Mileage: {self.mileage}
Color: {self.color}
Seating Capacity: {self.seating_capacity}
"""
if __name__ == "__main__":
C = Vehicle(100, 24)
C.assign_seating_capacity(20)
C.properties()
print(C)
D = Vehicle(55, 15, "black", 4)
print(D)
If you assign seating_capacity in the object init you won’t need the try/except in the properties function.
I added a repr function, which is what is called if you call print on an object.
Updated suggestion:
class Vehicle(object):
def __init__(self, maxspeed, mileage, brand, color="white"):
self.maxspeed=maxspeed
self.mileage=mileage
self.color=color
self.brand=brand
def assign_seating_capacity(self, seating_capacity):
self.seating_capacity=seating_capacity
def properties(self):
print(f"nProperties of the {self.brand} vehicle:")
print("Maximum Speed:", self.maxspeed)
print("Mileage:", self.mileage)
print("Color:", self.color)
try:
print("Seating Capacity:", self.seating_capacity)
except:
print("Seating Capacity unknown")
if __name__ == '__main__':
gm = Vehicle(100, 80000, 'GM','red')
gm.assign_seating_capacity(8)
ford = Vehicle(125, 100000,'FORD')
gm.properties()
ford.properties()
print('nUpdate:')
ford.mileage=75000
ford.seating_capacity=5
ford.properties()
del(ford.seating_capacity)
ford.properties()
Output:
Properties of the GM vehicle:
Maximum Speed: 100
Mileage: 80000
Color: red
Seating Capacity: 8
Properties of the FORD vehicle:
Maximum Speed: 125
Mileage: 100000
Color: white
Seating Capacity unknown
Update:
Properties of the FORD vehicle:
Maximum Speed: 125
Mileage: 75000
Color: white
Seating Capacity: 5
Properties of the FORD vehicle:
Maximum Speed: 125
Mileage: 75000
Color: white
Seating Capacity unknown
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
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
class Vehicle(object):
def __init__(self, maxspeed, mileage, color="white", seating_capacity=0):
self.maxspeed = maxspeed
self.mileage = mileage
self.color = color
self.seating_capacity = seating_capacity
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)
print("Seating Capacity:", self.seating_capacity)
def __repr__(self):
return f"""
Properties of the vehicle:
Maximum Speed {self.maxspeed}
Mileage: {self.mileage}
Color: {self.color}
Seating Capacity: {self.seating_capacity}
"""
if __name__ == "__main__":
C = Vehicle(100, 24)
C.assign_seating_capacity(20)
C.properties()
print(C)
D = Vehicle(55, 15, "black", 4)
print(D)
If you assign seating_capacity in the object init you won’t need the try/except in the properties function.
I added a repr function, which is what is called if you call print on an object.
Updated suggestion:
class Vehicle(object):
def __init__(self, maxspeed, mileage, brand, color="white"):
self.maxspeed=maxspeed
self.mileage=mileage
self.color=color
self.brand=brand
def assign_seating_capacity(self, seating_capacity):
self.seating_capacity=seating_capacity
def properties(self):
print(f"nProperties of the {self.brand} vehicle:")
print("Maximum Speed:", self.maxspeed)
print("Mileage:", self.mileage)
print("Color:", self.color)
try:
print("Seating Capacity:", self.seating_capacity)
except:
print("Seating Capacity unknown")
if __name__ == '__main__':
gm = Vehicle(100, 80000, 'GM','red')
gm.assign_seating_capacity(8)
ford = Vehicle(125, 100000,'FORD')
gm.properties()
ford.properties()
print('nUpdate:')
ford.mileage=75000
ford.seating_capacity=5
ford.properties()
del(ford.seating_capacity)
ford.properties()
Output:
Properties of the GM vehicle:
Maximum Speed: 100
Mileage: 80000
Color: red
Seating Capacity: 8
Properties of the FORD vehicle:
Maximum Speed: 125
Mileage: 100000
Color: white
Seating Capacity unknown
Update:
Properties of the FORD vehicle:
Maximum Speed: 125
Mileage: 75000
Color: white
Seating Capacity: 5
Properties of the FORD vehicle:
Maximum Speed: 125
Mileage: 75000
Color: white
Seating Capacity unknown
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