简体   繁体   English

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

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

I am receiving an error: 我收到一个错误:

AttributeError: type object 'Shop' has no attribute 'inventory' AttributeError:类型对象“ Shop”没有属性“ inventory”

my class is set: 我的课程已设置:

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

and I want to print inventory: 我想打印库存:

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

but keep getting the same error. 但仍然会出现相同的错误。 I can make it work with: 我可以使用它:

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

but am trying to make the switch to .format() 但我试图切换到.format()

You never created an instance of the class, so the Shop.__init__() method was never run either. 您从未创建过该类的实例 ,因此Shop.__init__()方法也从未运行过。

Your class doesn't have such an attribute; 您的班级没有这样的属性; the only attribute you defined for your Shop class is the __init__ method itself. 您为Shop类定义的唯一属性是__init__方法本身。

Create an instance of the class, then look for the attribute on that instance: 创建该类的实例,然后在该实例上查找属性:

# 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)

In creating the instance with Shop(....) , Python created the instance and called the __init__ method on that instance. 在使用Shop(....)创建实例时,Python创建了实例,并在该实例上调用了__init__方法。 As a result, the inventory attribute was added to the instance, and you can then access it via bikeshop.inventory . 结果, inventory属性被添加到实例,然后您可以通过bikeshop.inventory访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM