Calling a method using an argument

Jeremy Bowers jerf at jerf.org
Thu Feb 3 14:28:31 EST 2005


On Thu, 03 Feb 2005 15:48:05 +0000, C Gillespie wrote:

> Dear All,
> 
> I have a simple class
> class hello:
>     def world(self):
>         return 'hello'
>     def test(self,arg):
>         return self.arg
> 
> When I want to do is:
>>hello.test('world')
> 'hello'
> 
> i.e. pass the method name as an argument. How should I do this?

In addition to Diez's point, I'd also point out you can do that from
outside the class:

Python 2.3.4 (#1, Jan 25 2005, 21:29:33) 
[GCC 3.4.3  (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Simple:
...     def hello(self):        
...             print "hello"
... 
>>> s = Simple()
>>> getattr(s, "hello")()
hello
>>> 

which may be more useful depending on what you are doing. I mention this
because you are essentially re-implementing 'getattr' as a method of your
object and it is likely you don't *really* want to do that, but I don't
know, since we don't know what you are doing with this.



More information about the Python-list mailing list