[英]How to take the string from input of argparse and use it as an object
I am trying to create a program that reads a string off an argparse input and uses that string to call a certain object and use that object for the rest of the function. 我正在尝试创建一个程序,该程序会从argparse输入中读取一个字符串,并使用该字符串来调用某个对象,并将该对象用于其余的功能。
#!/usr/bin/python
import argparse
class car:
def __init__(self, color, year):
self.color = color
self.year = year
Beatle = car("blue", 1973)
parser = argparse.ArgumentParser()
parser.add_argument("--vehicleType")
args = parser.parse_args()
print("This "+args.vehicleType+ " is nice")
print("It was made:")
print(2018-args.vehicleType.year)
print("years ago")
However, I keep getting back this error: 但是,我一直在找回这个错误:
Traceback (most recent call last):
File "./test.py", line 17, in <module>
print(2018-args.vehicleType.year)
AttributeError: 'str' object has no attribute 'year'
I think the program is reading args.vehicleType as a string, while I want to read it in as an object. 我认为程序正在读取args.vehicleType作为字符串,而我想将其作为对象读取。 How do I get around this?
我该如何解决? -Cheers, and thanks in advance!
-干杯,并预先感谢! ~O.
〜O操作。 Fried
油炸
Would it be possible to actually create the object after? 之后可以实际创建对象吗? Something along these lines:
遵循以下原则:
#!/usr/bin/python
import argparse
class car:
def __init__(self, color, year, type):
self.color = color
self.year = year
self.type = type
parser = argparse.ArgumentParser()
parser.add_argument("--vehicleType") # Accept the argument as vehicle type.
args = parser.parse_args()
Beatle = car("blue", 1973, str(args.vehicleType)) # Now create the object.
print("This " + Beatle.type+ " is nice") # Use it here.
print("It was made:")
print(2018-Beatle.year) # And here.
print("years ago.")
Make a dictionary of cars 制作汽车词典
adict = {'beattle': car('blue',1973), 'ford': car('black', 1907),...}
yourcar = adict[args.vehicleType]
print(yourcar.year)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.