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

2
  • Is there a reason classobj is a class instance with attributes like "Bitcoin", instead of a dict with elements like "Bitcoin"? Commented Mar 8, 2018 at 20:27
  • Yeah I m using Django so that class is a model Commented Mar 8, 2018 at 20:50

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Should var be 'var' or is isinstance(var, str) True? (or do I not understand how getattr works)
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.