On Thu, Feb 9, 2012 at 2:23 PM, Tonu Mikk <tm...@umn.edu> wrote: > > > On Mon, Feb 6, 2012 at 12:58 PM, Dave Angel <d...@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
I haven't run this, but I think this is what is going on here: When you make the call to the method you don't include self. You have no self variable in your namespace, so it throws the error. However, when you write a method in a class, you need to declare the first argument self (its a convention to call it self. You could call it 'me', or anything -- but don't). self is the object itself. So do this: a1.doIt() a2.doIt() Alternately you could do this: MyApp.doIt(a1) In this case you are saying use the object a1 which is of the MyApp Class. But this looks weird > > test() > > When I run it, I get an error: > Traceback (most recent call last): > File "alan_class.py", line 22, in <module> > test() > 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 > tm...@umn.edu > > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor