instance has no attribute [closed]

2019-06-09 15:42发布

问题:

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.