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

asked Mar 3, 2014 at 21:49
2
  • In __init__: self.workerNo = wid - in your code the self. is missing. Common mistake. Commented Mar 3, 2014 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. Commented Mar 3, 2014 at 21:53

2 Answers 2

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.

answered Mar 3, 2014 at 21:50
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Mar 3, 2014 at 22:09

2 Comments

Thanks, this answer provided a solid explanation as to why there was an issue which has improved my understanding.
That's what we aim for! Glad it helped.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.