Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

Variable within a Variable in Python (3)

My head is probably in the wrong place with this, but I want to put a variable within a variable.

My goal for this script is to compare current versions of clients software with current software versions that are available from the vendor. At this stage I just want to print out what's available.

I have some def's setup with:

def v80(program_1 = '80.24', program_2 = '80.5', program_3 = '80.16'):
    pass
def v81(program_1 = '81.16', program_2 = '81.7', program_3 = '81.14'):
    pass
def v82(program_1 = '82.15', program_2 = '82.4', program_3 = '82.9'):
    pass
def v83(program_1 = '83.01', program_2 = '83.0', program_3 = '83.1'):
    pass

I'm then reading all of the clients versions from a text file and doing comparisons.

One of the vars I'm generating is "program_main", currently I'm doing something like:

If program_main == "83":
    if program_1:
        if v83['program_1'] > float(program_1):
            print ("Update available", program_1, "-->", v83[program_1])
    if program_2:
        if v83['program_2'] > float(program_2):
            print ("Update available", program_2, "-->", v83[program_2])
if program_main == "82"
    if program_1:
        if v82['program_1'] > float(program_1):
            print ("Update available", program_1, "-->", v82[program_1])

etc etc

My train of though would be something like

if program_1:
    if v[program_main] > float(program_1):
        print('Update available", program_1, "-->", v[program_main])

etc etc

I'm sure there's a much better way to do this entire setup, but this is one of my first proper python scripts so I'm happy to chalk it up to noobish-ness, just wanted to know what the right way of doing what I'm trying to achieve is.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can put your functions into a dictionary:

per_version = {
    '83': v83,
    '82': v82,
}

and simply use that to map string to function:

per_version[program_main]('program_1')

However, you may want to instead parameterise your version functions; make one function that takes the version as a parameter:

def program_check(version, program_1=None, program_2=None, program_3=None):
   # ...

which then looks up default values per program_x parameter based no the version, again from a dictionary perhaps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...