imattxc
imattxc

Reputation: 41

Python pass string to class using *args in __init__

I'm trying to learn python and wanted to attempt having multiple classes interact with each other. I want to store a string from class A in a variable of class b. I have been trying to use *args because I call the class other times without arguments. I cant seem to figure it out. I keep coming up with dead ends.

Here is my code

#!/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()

Can anyone tell me why Storage() is not seeing my argument? Sorry for the code length. I probably should have made an example.

Upvotes: 0

Views: 2622

Answers (1)

jkysam
jkysam

Reputation: 5779

It looks like you are confusing classes with object instances.

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()

By the way, when you call main() from within main(), it's a recursion not a return.

Upvotes: 1

Related Questions