1

Sometimes I don't know what will be operated by user.

class User(object):
    ...

    def get_name(self):
        return self.name

    def get_age(self):
        return self.age

operation = "http://localhost:8080/user/get_name".split('/')[-1]
user = User(...)

As you see, the operation is a variable name is as same as the class attribute.

I try:

eval('user.{}'.format(operation))

It can run. But it looks very appropriate

Now I want to handle it via a way like user.operation

How did I achieve it ?

agnewee
  • 100
  • 7
  • `user.__getattribute__(operation)` – rafaelc Sep 01 '16 at 03:39
  • 1
    Side-note: Python frowns on `get_x` functions. Either allow direct access to the attributes (if they're supposed to be mutable), or name the attribute `_name` (to indicate implementation details) and made an `@property` function named `name`, so you can access via `user.name` without needing parens. – ShadowRanger Sep 01 '16 at 03:54
  • In fact, if my class `Foo` has a attribute named `get_name()`, mybey i will get a variable `test` which value is `get_name`, so i want to execute it via `f = Foo() f.test()`. Perhaps this is not very clear expression – agnewee Sep 01 '16 at 05:16

1 Answers1

3

You can use getattr(). Apply like so:

getattr(user, operation)()

So now, the User instance, user will call operation from a string.

getattr will get the attribute of an object, user in this case. Then it will do user.operation, then execute with ().

Try it on IDEOne

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • 1
    Calling `__getattribute__` manually doesn't work quite as well as it might initally seem, because [if you call `__getattribute__` manually, you won't get the `__getattr__` fallback](http://stackoverflow.com/questions/39043912/python-3-getattribute-vs-dot-access-behaviour). Also, `foo.__getattribute__` does something different when `foo` is a class than when `foo` isn't a class. – user2357112 Sep 01 '16 at 03:56
  • @user2357112 You're correct, should I edit my answer to exclude `__getattribute__`? – Andrew Li Sep 01 '16 at 03:57
  • I'd leave out `__getattribute__`. `getattr` fits the general-purpose "get attribute value from attribute name string" job much better. It's rare that you'd want to call `__getattribute__` unless you're overriding it. – user2357112 Sep 01 '16 at 04:01
  • @user2357112 Ok, thanks for the advice! – Andrew Li Sep 01 '16 at 04:04