英文:
Beginner Classes - Calling a variable name in a function and if I used a try/except properly
问题
我刚刚开始学习Python/编程。我试图找到答案,但无法找到。所以我在我的实验室中创建了这个名为“Vehicle”的类的代码:
```python
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("车辆的属性:")
print("最大速度:", self.maxspeed)
print("里程:", self.mileage)
print("颜色:", self.color)
try:
print("座位容量:", self.seating_capacity)
except AttributeError:
print("座位容量未知")
然后我创建了几个对象,例如“vehicle1”、“vehicle2”等等。我的第一个问题是:有没有办法在“properties”函数中调用变量名称?所以,不是说“车辆的属性:”,而是说“vehicle1的属性:”?或者这太复杂了吗?
我的第二个问题是,我是否正确地使用了try/except?我以为我很聪明,绕过了如果在先使用“assign_seat_capacity”方法之前使用“properties”方法时发生的错误。但在我的实验室中,他们只是这样做:
class Vehicle:
color = "white"
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
self.seating_capacity = None
这样做是否更明智,还是无所谓呢?
提前感谢您阅读所有内容!<3
我不知道该怎么做,但我尝试了
print("Properties of", self, ":")
和name, self.name, variable - 即使我知道它们不会起作用
<details>
<summary>英文:</summary>
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
</details>
# 答案1
**得分**: 1
```python
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)
英文:
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.
答案2
得分: 1
如果你将你的车辆实例存储在一个列表中,那么你就可以有效地得到你想要的结果。而不是为每个车辆实例都有一个单独的变量,它只是列表中的一个偏移量。
例如:
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}'
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')
输出:
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
英文:
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
答案3
得分: 0
已更新建议:
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"\n{self.brand}车辆的属性:")
print("最大速度:", self.maxspeed)
print("里程:", self.mileage)
print("颜色:", self.color)
try:
print("座位容量:", self.seating_capacity)
except:
print("座位容量未知")
if __name__ == '__main__':
gm = Vehicle(100, 80000, 'GM', '红色')
gm.assign_seating_capacity(8)
ford = Vehicle(125, 100000, 'FORD')
gm.properties()
ford.properties()
print('\n更新:')
ford.mileage = 75000
ford.seating_capacity = 5
ford.properties()
del(ford.seating_capacity)
ford.properties()
输出:
GM车辆的属性:
最大速度: 100
里程: 80000
颜色: 红色
座位容量: 8
FORD车辆的属性:
最大速度: 125
里程: 100000
颜色: white
座位容量未知
更新:
FORD车辆的属性:
最大速度: 125
里程: 75000
颜色: white
座位容量: 5
FORD车辆的属性:
最大速度: 125
里程: 75000
颜色: white
座位容量未知
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论