实例没有属性 [英] instance has no attribute
问题描述
我是python的新手,正在努力理解为什么我在调用main()时不断收到"AttributeError:worker实例不具有'workerNo'属性."
im new to python and am struggling to understand why i keep getting "AttributeError: worker instance has no attribute 'workerNo'" when i call main().
beltLength = 5
class worker:
def __init__(self, wId):
workerNo = wId
def main():
production_Line = productionLine()
workers = []
for index in xrange(0, beltLength*2):
workers.append(worker(index))
print workers[index].workerNo
我的想法是,它应该在10个新的worker实例后面附加一个workerNo属性,该属性等于列表中的索引. 谢谢
My thinking is that it should append 10 new worker instances with a workerNo attribute which is equal to index in a list. Thanks
推荐答案
这里的问题是,当您应该使用实例变量时,您正在使用局部变量.
The issue here is that you are using a local variable when you should be using an instance variable.
调用函数或方法将创建一个新的名称空间,该名称空间仅在调用期间存在.为了使workerNo
(worker_no
的值根据 PEP 8 ,这是Python代码的标准),它必须保存在不会消失的命名空间中,以超出__init__()
方法的调用范围.
Calling a function or method creates a new namespace, which exists only for the duration of the call. In order for the value of workerNo
(worker_no
would be better according to PEP 8, the standard for Python code) to persist beyond the __init__()
method call it has to be stored in a namespace that doesn't evaporate.
每个实例都有一个这样的名称空间(在实例化其类时创建),并且每个方法调用的self
(第一个)参数都可以访问该名称空间.因此,在您的__init__()
方法中,您应该编写
Each instance has such a namespace (which is created when its class is instantiated), and the self
(first) argument to every method call gives access to that namespace. So in your __init__()
method you should write
self.workerNo = wId
,然后您可以从其他方法访问它(因为它们也收到引用同一个名称空间的self
参数.对实例的外部引用也可以访问实例属性.
and then you can access it from the other methods (since they also receive a self
argument referring to the same namespace. External references to the instance can also access the instance attributes.
这篇关于实例没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!