Python:在算术公式中使用类?

2024-04-26 11:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一门课:

class Bike(object):
    """Parent class for bikes"""

    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

# Bike designed for children"
bike1 = Bike("Trike", 20, 100)
# Bike designed for everyone"
bike2 = Bike("Kruzer", 50, 165)
# Bike designed for trick parks"
bike3 = Bike("BMX Bomber", 45, 350)
# Bike designed for backcountry trails"
bike4 = Bike("The Roamer", 40, 200)
# Bike designed for intensive mountain riding"
bike5 = Bike("The Avalanche", 70, 700)
# Bike designed for the handicapped"
bike6 = Bike("The Cadi", 120, 1500)

在另一个班级:

class Shop(object):
    """Parent class for bike shops"""

    def __init__(self, name, inventory, margin, profit):
        self.name = name
        self.inventory = inventory
        self.margin = margin
        self.profit = profit

但我似乎没法让它发挥作用:

 profit = Bike.cost * margin

它总是反馈一个错误,说“bike”没有定义,我假设这与“bike1=…,bike2=…”有关

该节是否应该缩进以便与类一起阻塞?或者这根本不是问题?你知道吗


Tags: thenamemarginselfforobjectdefclass
2条回答

你不能在算术公式中使用类!你知道吗

要访问对象的属性(例如bike1),请使用objectName.attributeName(例如bike1.cost)。你知道吗

要计算对象bike1代码的profit,请执行以下操作:

 profit = bike1.cost * margin

我很确定问题出在这里:

profit = bike(cost) * margin

内容如下:

profit = bike1.cost * margin

你需要指定自行车你不能只说自行车(成本)。如果你想对所有的自行车都这样做,我建议把所有的自行车都列在一个列表中,然后用for语句来检查这个列表。你知道吗

相关问题 更多 >