2

Here's a bit more context, in python, how could you create this effect?

import random
variable = 'randint'
random.[variable](1,3)

Is there any way to write a code for this effect? I haven't found anything outside of a load of {if} blocks.

Thanks!

2 Answers 2

4

You can use the getattr built-in:

>>> import random
>>> variable = 'randint'
>>> getattr(random, variable)(1, 3)
3
>>>

From the docs:

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

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

1 Comment

Thanks, that clears up my knowledge of the getattr function too.
0

just an alternative of using getattr:

In [141]: random.__dict__['randint'](1,3)
Out[141]: 3

1 Comment

Thanks, that may be useful for other stuff I'm working on as well.

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.