Calling class method by name passed in variable

Gary Herron gherron at islandtraining.com
Fri May 23 02:57:56 EDT 2008


Sagari wrote:
> Greetings,
>
> Can someone suggest an efficient way of calling method whose name is
> passed in a variable?
>
> Given something like:
>
> class X:
> #...
>   def a(self):
> # ...
>
>   def b(self):
> # ...
>
> #...
>
> x = X()
> #...
> v = 'a'
>
> How do I call the method of x  whose name is stored in v?
>   

Use getattr (stands for get attribute) to do this.

    fn = getattr(x, v)  # Get the method named by v
    fn(...)    # Call it

Or in one line:

    getattr(x,v)(...)


Gary Herron


> PHP code for this would be:
>
> class X {
>   function a() {
>   }
> }
>
> $x = new X();
> $v = 'a';
> $x->$v();
>
> I need a solution for Python. Could you suggest anything?
>
> The task it to call a function whose name is taken from user-supplied
> input.
>
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list
>   




More information about the Python-list mailing list