instance has no attribute [closed]

天大地大妈咪最大 提交于 2019-12-08 09:56:54

问题


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 

My thinking is that it should append 10 new worker instances with a workerNo attribute which is equal to index in a list. Thanks


回答1:


The issue here is that you are using a local variable when you should be using an instance variable.

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.

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

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.




回答2:


You need the self before your workerNo.

class worker:
    def __init__(self, wId):
        self.workerNo = wId

You should consider reading this excellent answer as to why.



来源:https://stackoverflow.com/questions/22158202/instance-has-no-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!