0

I am using Python 3.5 and wish to do something like this I have created a class which has variables Bitcoin, Monero , 'Etherum' ,etc with various integer values ,I wish to extract them

var1="Bitcoin"

value=classobj.var1 // there is a class which has a variable called Bitcoin and its value is 10 I wish to get its value using classobject.Bitcoin but the variable called var is Dynamic
print (value)

How do I achieve the same ?

EDIT

I know it is possible using switch statement but I am looking for other ways

shutup1
  • 159
  • 5
  • 16

1 Answers1

1

This is almost always a bad idea—and you really should explain why your design looks like this, because it's probably a bad design.

But "almost always" isn't "always", so Python has a way to do this:

getattr(classobj, var)
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • Should `var` be `'var'` or is `isinstance(var, str)` `True`? (or do I not understand how `getattr` works) – Garrett Gutierrez Mar 08 '18 at 20:31
  • `var` should be the variable `var`, not the string `'var'`. But yes, `isinstance(var, str)` should be true—as it is in the OP's question. If the value of `var` is a string, `'Bitcoin'`, then `getattr(classobj, var)` is the same as `getattr(classobj, 'Bitcoin')`, which is the same as `classobj.Bitcoin`. See [the docs](https://docs.python.org/3/library/functions.html#getattr). – abarnert Mar 08 '18 at 20:34