[Tutor] getting the current method name
Kristoffer Erlandsson
krier115@student.liu.se
Thu Apr 17 04:49:18 2003
On Thu, Apr 17, 2003 at 09:11:02AM +0200, Adam Groszer wrote:
> Dear All,
>
> how to do the following:
>
> class x:
> def y():
> print "Hi, my name is",<<method-name --> 'y'>>
>
> z=x()
> z.y()
> should print
> "Hi, my name is y"
>
> Of course, resolving "<<method-name --> 'y'>>" should not be done with
> simply 'y' :-)
Hello Adam,
Here are two ways to do it, but as you see using these methods you still have
to type the function name and make it function specific. As far as I know
functions in Python aren't self aware so you will have to reference it trough
its scope bound name, that is, you have to know the name of it in the code. I'm
not totally sure about this, but it's what everything seems like if i haven't
missed anything.
>>> class x:
... def y(self):
... print 'Hi, my name is', self.y.__name__
...
>>> z = x()
>>> z.y()
Hi, my name is y
>>> class x:
... def y(self):
... print 'Hi, my name is', getattr(self.y, '__name__')
...
>>> z = x()
>>> z.y()
Hi, my name is y
--
Kristoffer Erlandsson
E-mail: krier115@student.liu.se
ICQ#: 378225