Dynamically call methods where method is known by address vs name

Michael Selik michael.selik at gmail.com
Fri Jul 22 16:32:37 EDT 2016


On Fri, Jul 22, 2016 at 4:05 PM Malcolm Greene <python at bdurham.com> wrote:

> I know I can do the following:
>
> >>> s = 'lower'
> >>> getattr(s, 'upper')()
> 'LOWER'
>
> But how could I do the same if I had the method 'address' (better
> name???) vs. method name?
>
> >>> upper_method = s.upper
>
> How do I combine this upper_method with string s to execute the method
> and return 'LOWER'?
>

In [1]: s = 'hello'
In [2]: f = s.upper
In [3]: f()
Out[3]: 'HELLO'
In [4]: g = str.upper
In [5]: g(s)
Out[5]: 'HELLO'

Is that what you're looking for?



More information about the Python-list mailing list