[Python] Can I import the string as a variable name?

Asked 2 years ago, Updated 2 years ago, 23 views

class item:
    def __init__(self, name, value=0):
        self.name = name
        self.value = value

ClassitemRice = item("Rice", 2)

tradeItemSelect = ["Rice"] [#After that, various ingredients...]
for i in range(len(tradeItemSelect)):
    itemCount = 'item_{}'.format(tradeItemSelect[i]) # The value you want to get (just a variable)
    itemName = 'Classitem{}'.format(tradeItemSelect[i]).name # Value you want to get (class)

What I want to do is classitem{}.I want to get the value of name through the for statement.

I don't know much about Python, so I'm doing it while searching, but if I enter it like this,

'Classitem{}'.format(tradeItemSelect[i]).The name itself is recognized as a string and cannot get the value.

The exec and getattr are similar, but they're a little bit different.

How to use the for statement with the variable value of item_{} and classitem{}.Can I get the value of the name?

python

2022-09-22 18:20

1 Answers

Importing a string as a variable name means two tasks: (1) interpolating a string and (2) obtaining a class property with that string. Neither (especially in Python) is recommended.

I'm curious about the actual work you want to do. If it is:

Ramen...

# Not tested
totalAmount = 0
ingredients = []
ingredients.push(item('Rice', 2))
ingredients.push(item('Soy Sauce', 0.25))

for i in ingredients :
    TotalAmount += i.value # <-- Key
print ("Soy sauce rice totalAmount: " + str(totalAmount))")

I think this is enough.


2022-09-22 18:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.