我想在python中访问类函数中的args值。
例如,我在下面编写了一个示例测试程序。
#!/usr/bin/env python
import argparse
class Weather(object):
def __init__(self):
self.value = 0.0
def run(self):
print('in weather.run')
if (args.sunny == True):
print('It\'s Sunny')
else:
print('It\'s Not Sunny')
def main():
argparser = argparse.ArgumentParser(
description=__doc__)
argparser.add_argument(
'--sunny', action='store_true', dest='sunny', help='set if you want sunny weather')
args = argparser.parse_args()
print('args.sunny = ', args.sunny)
weather = Weather()
weather.run()
if __name__ == '__main__':
main()当我运行它(./test.py)时,我会看到下面的错误。
('args.sunny = ', False)
in weather.run
Traceback (most recent call last):
File "./test.py", line 30, in <module>
main()
File "./test.py", line 27, in main
weather.run()
File "./test.py", line 10, in run
if (args.sunny == True):
NameError: global name 'args' is not defined我尝试在Weather.run函数中添加“全局args”,但是得到了相同的错误。正确的方法是什么?
发布于 2019-11-15 08:09:30
您可以通过以下方式将其设置为全局的:
global args
args = argparser.parse_args()或者只是把阳光当作天气的论据:
def run(self, sunny):
.....
weather.run(self, args.sunny)发布于 2019-11-15 08:08:42
为什么不将main()中的任何内容添加到if语句中?
#!/usr/bin/env python
import argparse
class Weather(object):
def __init__(self):
self.value = 0.0
def run(self):
print('in weather.run')
if (args.sunny == True):
print('It\'s Sunny')
else:
print('It\'s Not Sunny')
if __name__ == '__main__':
argparser = argparse.ArgumentParser(
description=__doc__)
argparser.add_argument(
'--sunny', action='store_true', dest='sunny', help='set if you want sunny weather')
args = argparser.parse_args()
print('args.sunny = ', args.sunny)
weather = Weather()
weather.run()发布于 2020-06-30 21:53:27
所提供的两个答案与我的应用程序的设计不匹配,不过这对我来说很管用:
class Weather(object):
def run(self):
if (args.sunny == True):
print('It\'s Sunny')
else:
print('It\'s Not Sunny')
def main():
global args
args = argparser.parse_args()https://stackoverflow.com/questions/58872671
复制相似问题