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

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

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&#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;

def assign_seating_capacity(self, seating_capacity):
    self.seating_capacity=seating_capacity
    
def properties(self):
    print(&quot;Properties of the vehicle:&quot;)
    print(&quot;Maximum Speed:&quot;, self.maxspeed)
    print(&quot;Mileage:&quot;, self.mileage)
    print(&quot;Color:&quot;, self.color)
    try:
        print(&quot;Seating Capacity:&quot;, self.seating_capacity) 
    except AttributeError:
        print(&quot;Seating capacity unknown&quot;)

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?

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"

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! &lt;3

I had no idea what to do but I tried
print(&quot;Properties of&quot;, self, &quot;:&quot;)
and name, self.name, variable - even though I knew they wouldn&#39;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=&quot;white&quot;, 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(&quot;Properties of the vehicle:&quot;)
        print(&quot;Maximum Speed:&quot;, self.maxspeed)
        print(&quot;Mileage:&quot;, self.mileage)
        print(&quot;Color:&quot;, self.color)
        print(&quot;Seating Capacity:&quot;, self.seating_capacity)

    def __repr__(self):
        return f&quot;&quot;&quot;
        Properties of the vehicle:
        Maximum Speed {self.maxspeed}
        Mileage: {self.mileage}
        Color: {self.color}
        Seating Capacity: {self.seating_capacity}
        &quot;&quot;&quot;


if __name__ == &quot;__main__&quot;:
    C = Vehicle(100, 24)
    C.assign_seating_capacity(20)
    C.properties()
    print(C)
    D = Vehicle(55, 15, &quot;black&quot;, 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=&#39;white&#39;, 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) -&gt; str|int:
        return &#39;Unknown&#39; 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&#39;ID: {self._id}\nMax speed: {self.maxspeed}\nMileage: {self.mileage:,}\nColour: {self.colour}\nSeating capacity: {self.seating_capacity}\n&#39;

vehicles: list[Vehicle] = []

vehicles.append(Vehicle(150, 1))
vehicles.append(Vehicle(120, 15000, &#39;blue&#39;, 4))

print(*vehicles, sep=&#39;\n&#39;)

vehicles[0].seating_capacity = 5
vehicles[1].maxspeed = 145

print(&#39;---Data changed---&#39;)
print(*vehicles, sep=&#39;\n&#39;)

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=&quot;white&quot;):
        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&quot;\nProperties of the {self.brand} vehicle:&quot;)
        print(&quot;Maximum Speed:&quot;, self.maxspeed)
        print(&quot;Mileage:&quot;, self.mileage)
        print(&quot;Color:&quot;, self.color)
        
        try:
            print(&quot;Seating Capacity:&quot;, self.seating_capacity)
        except:
            print(&quot;Seating Capacity unknown&quot;)
            

if __name__ == &#39;__main__&#39;:
    
    gm = Vehicle(100, 80000, &#39;GM&#39;,&#39;red&#39;)
    gm.assign_seating_capacity(8)
    ford = Vehicle(125, 100000,&#39;FORD&#39;)
    
    gm.properties()
    ford.properties()
    
    print(&#39;\nUpdate:&#39;)
    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

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:

确定