1

I want to call the function bar() from the instance foo, just like this:

foo.bar()

But both instance and function names come from a given string. I tried getattr but it just let me use a string for the function, not the instance:

strbar = 'bar'    
getattr(foo, strbar)()

What I want to do is something like:

strfoo = 'foo'
strbar = 'bar'
getattr(strfoo, strbar)()

But it gives me:

AttributeError: 'str' object has no attribute 'bar'

I know a dictionary could be an option, but that makes me write a really long dictionary.

1 Answer 1

4

The best way would be to have a dictionary or a similar structure. However you could use eval which is evil. Or you can get your instance from the locals() dictionary:

getattr(locals()[instance_name], attribute_name)

I would think about redesigning your code. There must be a better solution as eval or locals ... like a dictionary ...

Sign up to request clarification or add additional context in comments.

6 Comments

Yes, eval() is potentially very dangerous if you're not careful about where you got that string and who can control its contents.
I'm confused at what's the user's trying do to here? Can anyone offer another example of doing this with a different approach to the code?
didn't get the first one but for a different approach we, or at least I, need some more information about what he's trying to do ..
Using the locals dictionary is exactly what I needed. But I read in a lot of places that using this is dangerous. Could you explain me why?
Especially writing to it can be very dangerous and is not reliable. However, reading from it is considered bad practice because you can just read anything in the local scope and not just the values you wanted to...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.