如何使用输入中的值填充属性?我有类似的东西。
class Names(object):
def __init__(self, name, nickname):
self.name = name
self.nickname = nickname
在另一堂课......
def userlog():
name = input("Your name: ")
nickname = input("Your nickname: ")
我需要将值放在此属性中并将它们保存到.txt文件中。
答案 0 :(得分:0)
试试这个:
def userlog():
name = input("Your name: ")
nickname = input("Your nickname: ")
provided_inputs = Names(name, nickname)
要将其保存在文本文件中,您可以像字符串一样尝试CSV格式。一种格式可能是“名称,昵称”
使用以下功能保存信息:
def write_to_file(file_path, text_to_write, write_type='wt'):
with open(file_path, write_type) as f:
f.write(text_to_write)
f.close()
准备好之后,请按照以下步骤修改userlog
功能:
def userlog():
.........
provided_inputs = Names(name, nickname) # This saves onto Names class
write_to_file('/tmp/you_path',
'{},{}'.format(name, nickname) # This saves the strings on a file
答案 1 :(得分:0)
您的问题包含两部分:
Names
要解决第一部分,在用户输入名称和昵称后,您可以创建一个新对象:
def userlog():
name = input("Your name: ")
nickname = input("Your nickname: ")
user = Names(name, nickname)
return user
对于第二部分,您需要打开一个文件进行写作,并以您喜欢的任何格式写出来:
user = userlog()
with open('output.txt', 'wt') as output_file:
output_file.write('Name: {}'.format(user.name))
output_file.write('Nick: {}'.format(user.nickname))