Python:错误=Class 'Foo'没有'bar'成员?

Python: Error = Class 'Foo' has no 'bar' member?

我收到一个错误:

AttributeError: 类型对象 'Shop' 没有属性 'inventory'

我的 class 已设置:

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


# Initial inventory including 2 of each 6 models available
inventory = 12
# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin

我想打印库存:

print "Mike's Bikes has {} bikes in stock.".format(Shop.inventory)

但不断出现同样的错误。我可以让它工作:

print "Mike's Bikes has %d bikes in stock." % (inventory)

但我正在尝试切换到 .format()

您从未创建 class 的 实例 ,因此 Shop.__init__() 方法也从未 运行。

你的class没有这样的属性;您为 Shop class 定义的唯一属性是 __init__ 方法本身。

创建 class 的实例,然后在该实例上查找属性:

# Initial inventory including 2 of each 6 models available
inventory = 12
# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin

bikeshop = Shop("Mike's Bikes", inventory, margin, profit)
print "Mike's Bikes has {} bikes in stock.".format(bikeshop.inventory)

在使用 Shop(....) 创建实例时,Python 创建了实例并在该实例上调用了 __init__ 方法。因此,inventory 属性被添加到实例中,然后您可以通过 bikeshop.inventory.

访问它