0

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

user3376646
  • 13
  • 1
  • 2
  • In `__init__`: `self.workerNo = wid` - in your code the `self.` is missing. Common mistake. – pasztorpisti Mar 03 '14 at 21:51
  • Aside: since you're using 2.7, you should always make your classes subclasses of `object`, i.e. `class worker(object):`. This will set free [magical ponies](http://stackoverflow.com/questions/2588628/what-is-the-purpose-of-subclassing-the-class-object-in-python). – DSM Mar 03 '14 at 21:53

2 Answers2

3

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.

Community
  • 1
  • 1
Nitish
  • 6,358
  • 1
  • 15
  • 15
0

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.

holdenweb
  • 33,305
  • 7
  • 57
  • 77