[Tutor] exercise with classes

Tonu Mikk tmikk at umn.edu
Thu Feb 9 20:23:43 CET 2012

On Mon, Feb 6, 2012 at 12:58 PM, Dave Angel <d at davea.name> wrote:

> On 02/06/2012 01:24 PM, Tonu Mikk wrote:
>> Now I get an error:  NameError: global name 'self' is not define.
>> Tonu
>>  Put your remarks after the stuff you quote.  You're top-posting, which
> makes the reply difficult to follow.
> Use copy/paste to describe an error message.  You retyped the one above,
> and added a typo.  Include the whole error, which includes the stack trace.
> If you had followed Nate's advice, you couldn't have gotten that error at
> all, so you'll also need to post the code that actually triggers the error.

Let's try this one more time.  I thought that I would try to make Alan's
code work.  Here is the version what I have now:

class Printer:
  def __init__(self,number=0):
     self.value = number
  def sayIt(self):
     print self.value

class MyApp:
  def __init__(self, aPrinter = None):
      if aPrinter == None:     # if no object passed create one
         aPrinter = Printer()
      self.obj = aPrinter      # assign object
  def doIt():
      self.obj.sayIt()         # use object

def test():
  p = Printer(42)
  a1 = MyApp()
  a2 = MyApp(p)   # pass p object into a2
  a1.doIt(self)   # prints default value = 0
  a2.doIt(self)   # prints 42, the value of p


When I run it, I get an error:
Traceback (most recent call last):
  File "alan_class.py", line 22, in <module>
  File "alan_class.py", line 19, in test
    a1.doIt(self)   # prints default value = 0
NameError: global name 'self' is not defined

> --
> DaveA

Tonu Mikk
Disability Services, Office for Equity and Diversity
612 625-3307
tmikk at umn.edu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120209/87329017/attachment.html>

More information about the Tutor mailing list