Python使用__init__中的* args将字符串传递给类

时间:2014-08-11 00:49:06

标签: python 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 个答案:

答案 0 :(得分: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()时,它是一个递归而不是返回。