简体   繁体   中英

Modifying and running function within a for loop Python

I am trying to run 3 different functions that has the form {}.result(). How can I use the getarr or another function so that the all 3 functions are ran within the for loop.

values = ["RSI", "MACD","ROCR"]
for k in values: 
   result= getattr(k).result()

Runs:

RSI.result()
MACD.result()
ROCR.result()

Rather than putting the names of the objects in a list, why don't you put the actual object in a list (actually a tuple here)?

for i in (RSI, MACD, ROCR):
    print(i.result())
class Values:
    RSI = 1
    MACD = 2
    ROCR = 3

values = Values()
names = ["RSI","MACD","ROCR"]

for i in names:
    print(getattr(values, i))

OUTPUT: 1 2 3

You will not be able to call getattr on your list as getattr gets a named attribute from your object which is equivalentof values.RSI of the code definition above. Otherwise you will get TypeError: getattr(): attribute name must be string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM