【问题标题】:Python: Error = Class 'Foo' has no 'bar' member?Python:错误=类'Foo'没有'bar'成员?
【发布时间】:2015-04-01 14:16:36
【问题描述】:

我收到一个错误:

AttributeError: type object '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()

【问题讨论】:

  • 你的 class 没有这样的属性;您从未创建过该类的实例。
  • self.inventory = 库存?
  • __init__ 方法在创建了实际的 self 实例时运行。您需要调用该类来创建实例。
  • 那么在开放代码中添加Shop()来实例化它?

标签: python class variables printing format


【解决方案1】:

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

你的 class 没有这样的属性;您为 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 访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    相关资源
    最近更新 更多