I recently picked up a copy of O’Reilly’s Learning Python, 3rd ed., which was published all of two months ago. I like it so far, but when I got to the part about user-defined classes and put this block of code into IDLE:
class Worker:
def __init__(self, name, pay):
self.name = name
self.pay = pay
def lastName(self):
return self.name.split()[-1]
def giveRaise(self, percent):
self.pay *= (1.0 + percent)
And then defined my workers, Jim and Sue:
jim = Worker('Jim Smith', 50000)
sue = Worker('Sue Jones', 60000)
My “name” and “pay” calls seemed to work:
>>> jim.name
'Jim Smith'
>>> sue.pay
60000
But then I tried to find Jim’s last name and give Sue a raise and got this:
>>> jim.lastName()
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
jim.lastName()
AttributeError: Worker instance has no attribute 'lastName'
>>> sue.giveRaise(.10)
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
sue.giveRaise(.10)
AttributeError: Worker instance has no attribute 'giveRaise'
In fact, running the same thing through PyAlaMode indicates that the only attributes available for jim and sue are: name, pay, class, dict, doc, init and module.
What’s the deal? Can anyone help me figure out what the problem is here?