首页 > 解决方案 > Why FLAGS is storing a value like other variables

问题描述

In the following code I am getting the error that None type object has no attribute x. When I run the following code by removing FLAGS it works fine. But I want to assign these values to the FLAGS because in my actual code I want to assign different values to the FLAGS. How can I fix this problem?

FLAGS = None
c1 =[1.5, 2.0, 2.5]

for i in range(len(c1)):
    FLAGS.x = c1[i]
    print(FLAGS.x)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--x', type=float, default=2.0)
    FLAGS = parser.parse_args()

标签: python

解决方案


Your code above if __name__ == '__main__': is being executed before the FLAGS variable has been initialized. Try something like this

import argparse

FLAGS = None
c1 =[1.5, 2.0, 2.5]

def main():
    for i in range(len(c1)):
        FLAGS.x = c1[i]
        print(FLAGS.x)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--x', type=float, default=2.0)
    FLAGS = parser.parse_args()
    main()

推荐阅读