我收到错误:
AttributeError:类型对象'Shop'没有属性'inventory'
我的课程设置为:
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()
答案 0 :(得分:7)
您从未创建过该类的实例,因此Shop.__init__()
方法也从未运行过。
您的类没有这样的属性;您为Shop
类定义的唯一属性是__init__
方法本身。
创建该类的实例,然后在该实例上查找该属性:
# 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
访问它。