Python user-defined class question

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?

It’s an indentation problem. You are defining lastName and giveRaise inside the definition of init, therefore they are local functions rather than class members, and will not be visible outside of init. To make them methods of the class, indent them so that they are at the same level as init.

Thanks. I’ve tried that, too, though; same problem. I also tried them inside init and then tried to call something like joe.init.lastName() (just for shits and giggles) and that didn’t work.

(I love the SDMB. You post a Python question and the first person to reply is Dutch! :cool: )

Your code works fine over here, after the indentation is fixed. I agree with Walton that it’s likely an identation problem — still.

It’s possible that you’ve got both tabs and spaces in your indents, and that this is confusing the Python parser. Something worth checking anyway.

Hrm. I’m pretty sure I didn’t, but I’ll try it again anyway.

If that doesn’t work, maybe I’ll uninstall and reinstall Python, or something; if the code works over there and doesn’t work over here, there’s obviously a problem with my implementation somehow.

…Well, I’ll be damned. After a reboot, it works fine in IDLE (with the indentation fixed).

If you recognize the name “Raymond Luxury Yacht,” you are a member of the Python class.