Calling a method using an argument

C

C Gillespie

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?

Thanks

Colin
 
D

Diez B. Roggisch

Diez said:
def test(self,arg):
return getattr(self, arg)

Oops, missed the calling:

def test(self,arg):
return getattr(self, arg)()


If you have more args, do this:

def test(self, *args):
return getattr(self, args[0])(*args[1:])
 
D

Duncan Booth

Diez said:
If you have more args, do this:

def test(self, *args):
return getattr(self, args[0])(*args[1:])

This would be cleaner written as:

def test(self, method, *args):
return getattr(self, method)(*args)

and for complete generality:

def test(self, method, *args, **kw):
return getattr(self, method)(*args, **kw)
 
J

Jeremy Bowers

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'

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..... def hello(self):
.... print "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.
 
C

C Gillespie

Dear All,

Many thanks

Colin
C Gillespie said:
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'

i.e. pass the method name as an argument. How should I do this?

Thanks

Colin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,219
Messages
2,571,117
Members
47,730
Latest member
scavoli

Latest Threads

Top