[Tutor] problem with class - get message that self is not defined
Alan Gauld
alan.gauld at freenet.co.uk
Tue May 23 00:07:27 CEST 2006
> When I try to use the class listed below, I get the statement that
> self
> is not defined.
>
> test=TriggerMessage(data)
> var = test.decode(self.qname)
>
> I would have thought that self would have carried forward when I
> grabbed
> an instance of TriggerMessage.
self is a special varianble that is only defined inside of a
method of an object. It refers to the object itself (hence the name!)
Thus you cannot pass self.qname into a method unless you are
already inside another object's method.
You can read about this in more edetail in the OOP topic
of my tutor but I'll try to illustrate here:
class C:
def method(self,x):
self.var = x
def g(self, anObj):
anObj.f(self.var)
class D:
def f(self, val):
print val
c = C()
c.method(42)
creates an object called c and executes its method with a
value of 42. This executes the function
C.method(c,42)
where self takes the values c and x 42
The end result is that object c has a data member
called var with the value 42
d = D()
c.g(d)
creates a new object d
calls the g method of c passing object d as argument
executes the function
C.g(c,d)
where self takes on the value c and anObj takes on d
C.g() then calls d.f(self.var) which executes
D.f(d,c.var)
that is, the self in D.f() is d and the self in C.g() = c
I hope that makes sense.
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list