初学者课程 – 在函数中调用变量名称,以及如果我正确使用了try/except

huangapple go评论129阅读模式
英文:

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

问题

  1. 我刚刚开始学习Python/编程我试图找到答案但无法找到所以我在我的实验室中创建了这个名为Vehicle的类的代码
  2. ```python
  3. class Vehicle(object):
  4. def __init__(self, maxspeed, mileage, color="white"):
  5. self.maxspeed=maxspeed;
  6. self.mileage=mileage;
  7. self.color=color;
  8. def assign_seating_capacity(self, seating_capacity):
  9. self.seating_capacity=seating_capacity
  10. def properties(self):
  11. print("车辆的属性:")
  12. print("最大速度:", self.maxspeed)
  13. print("里程:", self.mileage)
  14. print("颜色:", self.color)
  15. try:
  16. print("座位容量:", self.seating_capacity)
  17. except AttributeError:
  18. print("座位容量未知")

然后我创建了几个对象,例如“vehicle1”、“vehicle2”等等。我的第一个问题是:有没有办法在“properties”函数中调用变量名称?所以,不是说“车辆的属性:”,而是说“vehicle1的属性:”?或者这太复杂了吗?

我的第二个问题是,我是否正确地使用了try/except?我以为我很聪明,绕过了如果在先使用“assign_seat_capacity”方法之前使用“properties”方法时发生的错误。但在我的实验室中,他们只是这样做:

  1. class Vehicle:
  2. color = "white"
  3. def __init__(self, max_speed, mileage):
  4. self.max_speed = max_speed
  5. self.mileage = mileage
  6. self.seating_capacity = None

这样做是否更明智,还是无所谓呢?
提前感谢您阅读所有内容!<3

我不知道该怎么做,但我尝试了
print("Properties of", self, ":")
和name, self.name, variable - 即使我知道它们不会起作用

  1. <details>
  2. <summary>英文:</summary>
  3. I just started learning Python/coding in general. I tried to find an answer to this but couldn&#39;t. So I created this code for a Class &quot;Vehicle&quot; in my lab:

class Vehicle(object):
def init(self, maxspeed, mileage, color="white"):
self.maxspeed=maxspeed;
self.mileage=mileage;
self.color=color;

  1. def assign_seating_capacity(self, seating_capacity):
  2. self.seating_capacity=seating_capacity
  3. def properties(self):
  4. print(&quot;Properties of the vehicle:&quot;)
  5. print(&quot;Maximum Speed:&quot;, self.maxspeed)
  6. print(&quot;Mileage:&quot;, self.mileage)
  7. print(&quot;Color:&quot;, self.color)
  8. try:
  9. print(&quot;Seating Capacity:&quot;, self.seating_capacity)
  10. except AttributeError:
  11. print(&quot;Seating capacity unknown&quot;)
  1. And then I created a few objects, &quot;vehicle1&quot;, vehicle2&quot; and so forth. My first question: is there a way to call a variable name in the function &quot;properties&quot;? So instead of saying &quot;Properties of the vehicle:&quot; it would say &quot;Properties of vehicle1:&quot;? Or is that way too complicated?
  2. 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 &quot;properties&quot; method without first using the &quot;assign_seat_capacity&quot; one. But in my lab they just did it like this:

class Vehicle:
color = "white"

  1. def __init__(self, max_speed, mileage):
  2. self.max_speed = max_speed
  3. self.mileage = mileage
  4. self.seating_capacity = None
  1. Is it smarter to do it this way or does it not really matter?
  2. Thank you in advance for reading all of this! &lt;3
  3. I had no idea what to do but I tried
  4. print(&quot;Properties of&quot;, self, &quot;:&quot;)
  5. and name, self.name, variable - even though I knew they wouldn&#39;t work
  6. </details>
  7. # 答案1
  8. **得分**: 1
  9. ```python
  10. class Vehicle(object):
  11. def __init__(self, maxspeed, mileage, color="white", seating_capacity=0):
  12. self.maxspeed = maxspeed
  13. self.mileage = mileage
  14. self.color = color
  15. self.seating_capacity = seating_capacity
  16. def assign_seating_capacity(self, seating_capacity):
  17. self.seating_capacity = seating_capacity
  18. def properties(self):
  19. print("Properties of the vehicle:")
  20. print("Maximum Speed:", self.maxspeed)
  21. print("Mileage:", self.mileage)
  22. print("Color:", self.color)
  23. print("Seating Capacity:", self.seating_capacity)
  24. def __repr__(self):
  25. return f"""
  26. Properties of the vehicle:
  27. Maximum Speed {self.maxspeed}
  28. Mileage: {self.mileage}
  29. Color: {self.color}
  30. Seating Capacity: {self.seating_capacity}
  31. """
  32. if __name__ == "__main__":
  33. C = Vehicle(100, 24)
  34. C.assign_seating_capacity(20)
  35. C.properties()
  36. print(C)
  37. D = Vehicle(55, 15, "black", 4)
  38. print(D)
英文:
  1. class Vehicle(object):
  2. def __init__(self, maxspeed, mileage, color=&quot;white&quot;, seating_capacity=0):
  3. self.maxspeed = maxspeed
  4. self.mileage = mileage
  5. self.color = color
  6. self.seating_capacity = seating_capacity
  7. def assign_seating_capacity(self, seating_capacity):
  8. self.seating_capacity = seating_capacity
  9. def properties(self):
  10. print(&quot;Properties of the vehicle:&quot;)
  11. print(&quot;Maximum Speed:&quot;, self.maxspeed)
  12. print(&quot;Mileage:&quot;, self.mileage)
  13. print(&quot;Color:&quot;, self.color)
  14. print(&quot;Seating Capacity:&quot;, self.seating_capacity)
  15. def __repr__(self):
  16. return f&quot;&quot;&quot;
  17. Properties of the vehicle:
  18. Maximum Speed {self.maxspeed}
  19. Mileage: {self.mileage}
  20. Color: {self.color}
  21. Seating Capacity: {self.seating_capacity}
  22. &quot;&quot;&quot;
  23. if __name__ == &quot;__main__&quot;:
  24. C = Vehicle(100, 24)
  25. C.assign_seating_capacity(20)
  26. C.properties()
  27. print(C)
  28. D = Vehicle(55, 15, &quot;black&quot;, 4)
  29. 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

如果你将你的车辆实例存储在一个列表中,那么你就可以有效地得到你想要的结果。而不是为每个车辆实例都有一个单独的变量,它只是列表中的一个偏移量。

例如:

  1. class Vehicle:
  2. _id = -1
  3. def __init__(self, maxspeed: int, mileage: int, colour: str='white', seating_capacity: int|None=None):
  4. self.maxspeed = maxspeed
  5. self.mileage = mileage
  6. self.colour = colour
  7. self._seating_capacity = seating_capacity
  8. Vehicle._id += 1
  9. self._id = Vehicle._id
  10. @property
  11. def seating_capacity(self) -> str|int:
  12. return 'Unknown' if self._seating_capacity is None else self._seating_capacity
  13. @seating_capacity.setter
  14. def seating_capacity(self, value: int):
  15. self._seating_capacity = value
  16. def __str__(self):
  17. return f'ID: {self._id}\nMax speed: {self.maxspeed}\nMileage: {self.mileage:,}\nColour: {self.colour}\nSeating capacity: {self.seating_capacity}'
  18. vehicles: list[Vehicle] = []
  19. vehicles.append(Vehicle(150, 1))
  20. vehicles.append(Vehicle(120, 15000, 'blue', 4))
  21. print(*vehicles, sep='\n')
  22. vehicles[0].seating_capacity = 5
  23. vehicles[1].maxspeed = 145
  24. print('---Data changed---')
  25. print(*vehicles, sep='\n')

输出:

  1. ID: 0
  2. Max speed: 150
  3. Mileage: 1
  4. Colour: white
  5. Seating capacity: Unknown
  6. ID: 1
  7. Max speed: 120
  8. Mileage: 15,000
  9. Colour: blue
  10. Seating capacity: 4
  11. ---Data changed---
  12. ID: 0
  13. Max speed: 150
  14. Mileage: 1
  15. Colour: white
  16. Seating capacity: 5
  17. ID: 1
  18. Max speed: 145
  19. Mileage: 15,000
  20. Colour: blue
  21. 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:

  1. class Vehicle:
  2. _id = -1
  3. def __init__(self, maxspeed: int, mileage: int, colour: str=&#39;white&#39;, seating_capacity: int|None=None):
  4. self.maxspeed = maxspeed
  5. self.mileage = mileage
  6. self.colour = colour
  7. self._seating_capacity = seating_capacity
  8. Vehicle._id += 1
  9. self._id = Vehicle._id
  10. @property
  11. def seating_capacity(self) -&gt; str|int:
  12. return &#39;Unknown&#39; if self._seating_capacity is None else self._seating_capacity
  13. @seating_capacity.setter
  14. def seating_capacity(self, value: int):
  15. self._seating_capacity = value
  16. def __str__(self):
  17. return f&#39;ID: {self._id}\nMax speed: {self.maxspeed}\nMileage: {self.mileage:,}\nColour: {self.colour}\nSeating capacity: {self.seating_capacity}\n&#39;
  18. vehicles: list[Vehicle] = []
  19. vehicles.append(Vehicle(150, 1))
  20. vehicles.append(Vehicle(120, 15000, &#39;blue&#39;, 4))
  21. print(*vehicles, sep=&#39;\n&#39;)
  22. vehicles[0].seating_capacity = 5
  23. vehicles[1].maxspeed = 145
  24. print(&#39;---Data changed---&#39;)
  25. print(*vehicles, sep=&#39;\n&#39;)

Output:

  1. ID: 0
  2. Max speed: 150
  3. Mileage: 1
  4. Colour: white
  5. Seating capacity: Unknown
  6. ID: 1
  7. Max speed: 120
  8. Mileage: 15,000
  9. Colour: blue
  10. Seating capacity: 4
  11. ---Data changed---
  12. ID: 0
  13. Max speed: 150
  14. Mileage: 1
  15. Colour: white
  16. Seating capacity: 5
  17. ID: 1
  18. Max speed: 145
  19. Mileage: 15,000
  20. Colour: blue
  21. Seating capacity: 4

答案3

得分: 0

已更新建议:

  1. class Vehicle(object):
  2. def __init__(self, maxspeed, mileage, brand, color="white"):
  3. self.maxspeed = maxspeed
  4. self.mileage = mileage
  5. self.color = color
  6. self.brand = brand
  7. def assign_seating_capacity(self, seating_capacity):
  8. self.seating_capacity = seating_capacity
  9. def properties(self):
  10. print(f"\n{self.brand}车辆的属性:")
  11. print("最大速度:", self.maxspeed)
  12. print("里程:", self.mileage)
  13. print("颜色:", self.color)
  14. try:
  15. print("座位容量:", self.seating_capacity)
  16. except:
  17. print("座位容量未知")
  18. if __name__ == '__main__':
  19. gm = Vehicle(100, 80000, 'GM', '红色')
  20. gm.assign_seating_capacity(8)
  21. ford = Vehicle(125, 100000, 'FORD')
  22. gm.properties()
  23. ford.properties()
  24. print('\n更新:')
  25. ford.mileage = 75000
  26. ford.seating_capacity = 5
  27. ford.properties()
  28. del(ford.seating_capacity)
  29. ford.properties()

输出:

  1. GM车辆的属性
  2. 最大速度 100
  3. 里程 80000
  4. 颜色 红色
  5. 座位容量 8
  6. FORD车辆的属性
  7. 最大速度 125
  8. 里程 100000
  9. 颜色 white
  10. 座位容量未知
  11. 更新
  12. FORD车辆的属性
  13. 最大速度 125
  14. 里程 75000
  15. 颜色 white
  16. 座位容量 5
  17. FORD车辆的属性
  18. 最大速度 125
  19. 里程 75000
  20. 颜色 white
  21. 座位容量未知
英文:

Updated suggestion:

  1. class Vehicle(object):
  2. def __init__(self, maxspeed, mileage, brand, color=&quot;white&quot;):
  3. self.maxspeed=maxspeed
  4. self.mileage=mileage
  5. self.color=color
  6. self.brand=brand
  7. def assign_seating_capacity(self, seating_capacity):
  8. self.seating_capacity=seating_capacity
  9. def properties(self):
  10. print(f&quot;\nProperties of the {self.brand} vehicle:&quot;)
  11. print(&quot;Maximum Speed:&quot;, self.maxspeed)
  12. print(&quot;Mileage:&quot;, self.mileage)
  13. print(&quot;Color:&quot;, self.color)
  14. try:
  15. print(&quot;Seating Capacity:&quot;, self.seating_capacity)
  16. except:
  17. print(&quot;Seating Capacity unknown&quot;)
  18. if __name__ == &#39;__main__&#39;:
  19. gm = Vehicle(100, 80000, &#39;GM&#39;,&#39;red&#39;)
  20. gm.assign_seating_capacity(8)
  21. ford = Vehicle(125, 100000,&#39;FORD&#39;)
  22. gm.properties()
  23. ford.properties()
  24. print(&#39;\nUpdate:&#39;)
  25. ford.mileage=75000
  26. ford.seating_capacity=5
  27. ford.properties()
  28. del(ford.seating_capacity)
  29. ford.properties()

Output:

  1. Properties of the GM vehicle:
  2. Maximum Speed: 100
  3. Mileage: 80000
  4. Color: red
  5. Seating Capacity: 8
  6. Properties of the FORD vehicle:
  7. Maximum Speed: 125
  8. Mileage: 100000
  9. Color: white
  10. Seating Capacity unknown
  11. Update:
  12. Properties of the FORD vehicle:
  13. Maximum Speed: 125
  14. Mileage: 75000
  15. Color: white
  16. Seating Capacity: 5
  17. Properties of the FORD vehicle:
  18. Maximum Speed: 125
  19. Mileage: 75000
  20. Color: white
  21. Seating Capacity unknown

huangapple
  • 本文由 发表于 2023年7月10日 11:00:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650445.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定