簡體   English   中英

Python使用__init__中的* args將字符串傳遞給類

[英]Python pass string to class using *args in __init__

我正在嘗試學習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()沒有看到我的論點? 對不起,代碼長度。 我大概應該舉一個例子。

看起來您正在將類與對象實例混淆。

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()時,這是遞歸而不是返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM