python using variables from another file

后端 未结 2 1503
时光说笑
时光说笑 2020-11-27 04:03

I\'m new and trying to make a simple random sentence generator- How can I pull a random item out of a list that is stored in another .py document? I\'m using

         


        
2条回答
  •  日久生厌
    2020-11-27 04:11

    You can import the variables from the file:

    vardata.py

    verb_list = [x, y, z]
    other_list = [1, 2, 3]
    something_else = False
    

    mainfile.py

    from vardata import verb_list, other_list
    import random
    
    print random.choice(verb_list) 
    

    you can also do:

    from vardata import *
    

    to import everything from that file. Be careful with this though. You don't want to have name collisions.

    Alternatively, you can just import the file and access the variables though its namespace:

    import vardata
    print vardata.something_else
    

提交回复
热议问题