0

Can the "first-class" concept be applied to Python methods/attributes like it can functions?

>>>a=sum
>>>a([1,2,3])
6

I would like to do something like:

>>>case='lower'
>>>'UPPERCASE'.case()

To produce the string object 'uppercase'. Otherwise, would I just have to use eval?

LMc
  • 12,577
  • 3
  • 31
  • 43
  • 2
    Sure; `getattr('UPPERCASE', case)()` would give `'uppercase'` (see e.g. http://stackoverflow.com/q/2612610/3001761). Note that your examples aren't equivalent, though; in the first you assign the function itself, in the second you assign a method's *name*. More appropriate might be `case = str.lower`, then you want `case('UPPERCASE')`. – jonrsharpe Jul 11 '16 at 22:43
  • Well you certainly cannot add / change methods of string objects, if you were to subclass `str` then you could define `case = str.lower` inside the class definition, then `MyStr('UPPERCASE').case() -> 'uppercase'` – Tadhg McDonald-Jensen Jul 11 '16 at 22:49
  • what "first-class" concept exactly means? – mhbashari Jul 11 '16 at 23:04
  • 1
    @mhbashari see e.g. http://stackoverflow.com/q/705173/3001761 – jonrsharpe Jul 12 '16 at 21:47

1 Answers1

0

You can do it this way:

case = str.lower # Take the lower() method of the str class.
case('UPPERCASE') # pass your string as the first argument, which is self.

In this case, Python being explicit about self being the first argument to methods makes this a lot clearer to understand.

Jim
  • 72,985
  • 14
  • 101
  • 108