在__init__中使用*args将字符串传递给类
我正在学习Python,想尝试让多个类互相交流。我想把类A中的一个字符串存储到类B的一个变量里。我一直在尝试使用 *args,因为我在其他地方调用这个类时没有传递参数。但我似乎搞不清楚怎么做,总是遇到瓶颈。
这是我的代码
#!/usr/bin/python
# import modules used here
import sys
# import encrypt
# import storage
class Storage(object):
def __init__(self, *args):
if len(args) > 1:
store(args[0].usr_string)
self.data = {}
def store(var):
Storage().data[len(data)] = [var]
print "store function successfully called. stored: %s" % (var)
def retrieve(self):
return str(Storage().data.items())
print "retrieve function successfully called"
class Dialogue(object):
# global usr_string
def __init__(self):
self.variable = 1
def welcome(self):
print 'Would you like to store a new string? (1): '
print 'Would you like to view your stored strings? (2): '
print 'Would you like to terminate this session? (3): '
# prprint 'usr_string is now:'+get_new_stringint 'usr_string is now:'+usr_string
return raw_input(': ')
def new_string(self):
print 'You may type your string in below'
return raw_input(': ')
# def disp_string_list(self):
# # list = defg.retrieve()
# print str(list)
def main():
def __init__(self):
self.usr_string
self.selec
selec = Dialogue().welcome()
if int(selec) == 1: #store new string
main().usr_string = Dialogue().new_string() #requests usr for string
tempObj = main()
Storage(tempObj)
""" passes main object to Storage class to store main.usr_string"""
main() #return to menu
elif int(selec) == 2: #view stored string
temp = Storage().retrieve()
print temp
# Dialogue().disp_string_list() #recall list of strings from storage
main() #return to menu
else: #exit on bad response or quit
sys.exit()
if __name__ == '__main__': #call main func after module fully loads
main()
有没有人能告诉我为什么Storage()看不到我的参数?抱歉代码有点长,我可能应该做个简单的例子。
1 个回答
1
看起来你把类和对象实例搞混了。
class Storage(object):
def __init__(self):
self.data = []
class Dialogue(object):
def __init__(self):
self.msg = 'hello world'
def main():
d = Dialogue()
s = Storage()
s.data.append(d.msg)
print s.data
if __name__ == '__main__':
main()
顺便说一下,当你在main()里面调用main()的时候,这其实是递归,而不是返回。