我在將一個類實例中定義的變量傳遞給另一個類實例時遇到問題。我對使用類相對來說比較陌生,但我的理解是,通過簡單定義類實例的一部分(如下例),就可以將變量從一個實例傳遞到另一個實例。儘管過去我使用過這個模型,但我從來沒有試過用GUI框架(例如wxPython
)來做這件事。使用Python將變量從一個類實例傳遞到另一個類實例?
class Foo(object):
def __init__(self, var):
self.var = var
class Bar(object):
def do_something(self, var):
print var*3
if __name__ == '__main__':
f = Foo(3)
b = Bar()
b.do_something(f.var)
我遇到的問題是,wxPython的實例似乎是預先定義,將不接受任何額外的參數(讓我只能傳遞之類的標題,大小等)的類實例。
我面對的另一個問題是我試圖通過調用一個對話框窗口深入傳遞變量三個類,並從對話框我調用一個單獨的類,旨在啓動一個工作線程。
所以我的問題是:
如何從第一個類的實例變量傳遞給第三類實例?
如何覆蓋wxPython實例以允許定義附加變量?
或者,有可能創建一個自定義事件處理程序來傳遞必要的數據嗎?
爲了澄清...
我使用Python和願想,我懂得編程使用類與框架,如Tkinter的和wxPython的GUI的基本面(在此使用項目)。我寫了一個主類/實例,它從用戶那裏獲取一些數據,我希望能夠傳遞存儲在self.main_instance_var中的信息並將其傳遞給第二個類/實例(在這種情況下爲進度對話框窗口
當我試圖在我的進度對話框中使用上述模型時,我得到了一個非常不明確的語法錯誤('關鍵字arg'後面的'non-keyword arg'),防止我進一步傳遞變量到工作線程進程對話框窗口,如果我已經得到了那會是一回事,但語法錯誤,我不明白一個例外看下面一個簡單的例子:。
class ProgressDialog(wx.Dialog):
def __init__(self, parent, title, myVar): # Generates syntax error on this line
super(ProgressDialog, self).__init__(parent=parent,
title=title, size=(500, 110))
self.var = myVar
基本源(由REQ uest,對不起它這麼髒):
import time
import os, sys, wx
from ftplib import FTP_TLS
from threading import Thread
from wx.lib.pubsub import Publisher
########################################################################
class FtpValues(object):
""" Returns a property attribute - called by FtpFileTransfer
Used to set values/variables for Host, USERID, PASSWD, FILE """
#----------------------------------------------------------------------
def __init__(self):
self.varList = None
#----------------------------------------------------------------------
def GetValues(self):
return self.varList
#----------------------------------------------------------------------
def SetValues(self, HOST, USERID, PASSWD, FILE):
self.varList = [HOST, USERID, PASSWD, FILE]
#----------------------------------------------------------------------
def DelValues(self):
del self.valList
Values = property(GetValues, SetValues, DelValues, "Set/Get FtpValues")
# http://docs.python.org/library/functions.html#property
########################################################################
class FtpFileTransfer(Thread):
"""Test Worker Thread Class."""
#----------------------------------------------------------------------
def __init__(self):
"""Init Worker Thread Class."""
Thread.__init__(self)
self.StartTransfer() # start the thread
#----------------------------------------------------------------------
def StartTransfer(self): # was named run - started automatically
"""Run Worker Thread.""" # when called by the start method
# This is the code executing in the new thread.
HOST, USERID, PASSWD, FILE = FtpValues.Values
BLOCKSIZE = 57344
try:
ftp = FTP_TLS(HOST)
ftp.login(USERID, PASSWD)
ftp.prot_p()
ftp.voidcmd("TYPE I")
f = open(FILE, 'rb')
datasock, esize = ftp.ntransfercmd(
'STOR %s' % os.path.basename(FILE))
size = os.stat(FILE)[6]
bytes_so_far = 0
while 1:
buf = f.read(BLOCKSIZE)
if not buf:
break
datasock.sendall(buf)
bytes_so_far += len(buf)
msg = [bytes_so_far, size]
Publisher().sendMessage("update", msg)
except: raise
finally:
try:
datasock.close()
f.close()
ftp.voidresp()
ftp.quit()
print 'Complete...'
except: pass
wx.CallAfter(Publisher().sendMessage, "update", "Database Transfer Complete!")
########################################################################
class ProgressDialog(wx.Dialog):
def __init__(self, parent, title):
super(ProgressDialog, self).__init__(parent=parent,
title=title, size=(500, 110))
self.displayLbl = wx.StaticText(self, -1, 'Verifying Database Files... ', (20, 20)) #Preparing for Transfer...
self.gauge = wx.Gauge(self, -1, 100, (20, 45), (370, 24))
self.btn = btn = wx.Button(self, -1, 'Cancel', (400, 45), (-1, 25))
btn.Bind(wx.EVT_BUTTON, self.OnClose)
# listens for response from worker thread
Publisher().subscribe(self.updateDisplay, "update")
FtpFileTransfer()#.StartTransfer(HOST, USERID, PASSWD, FILE) #Start the FTP Worker Thread
#self.OnStart()
#----------------------------------------------------------------------
def run(self):
FtpFileTransfer(HOST, USERID, PASSWD, FILE)
#----------------------------------------------------------------------
def OnClose(self, event):
""" Place Holder """
if self.btn.GetLabel() == 'Finish':
# Do Something!
pass
return None
#----------------------------------------------------------------------
def updateDisplay(self, msg):
""" Receives data from thread and updates the display """
if isinstance(msg.data, list):
bytes_so_far, size = msg.data
k = 100 * bytes_so_far/size
self.displayLbl.SetLabel("Sent %d of %d bytes %.1f%%" % (bytes_so_far, size, 100 * bytes_so_far/size))
self.gauge.SetValue(k)
else:
self.displayLbl.SetLabel("%s" % msg.data)
#self.btn.Enable()
self.btn.SetLabel('Finish')
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
self.displayLbl = wx.StaticText(panel, label="Amount of time since thread started goes here")
self.btn = btn = wx.Button(panel, label="Start Thread")
self.gauge = wx.Gauge(panel, -1, 100, size=(370, 24))
btn.Bind(wx.EVT_BUTTON, self.onButton)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.displayLbl, 0, wx.ALL|wx.CENTER, 5)
sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
sizer.Add(self.gauge, 0, wx.ALL|wx.CENTER, 5)
panel.SetSizer(sizer)
self.VarData()
# create a pubsub receiver
Publisher().subscribe(self.updateDisplay, "update")
#----------------------------------------------------------------------
def onButton(self, event):
"""
Runs the thread
"""
chgdep = ProgressDialog(None, title='File Transfer. . .')
chgdep.ShowModal()
#chgdep.Destroy()
#----------------------------------------------------------------------
def updateDisplay(self, msg):
"""
Receives data from thread and updates the display
"""
if isinstance(msg.data, list):
bytes_so_far, size = msg.data
k = 100 * bytes_so_far/size
self.displayLbl.SetLabel("Sent %d of %d bytes %.1f%%" % (bytes_so_far, size, 100 * bytes_so_far/size))
self.gauge.SetValue(k)
else:
self.displayLbl.SetLabel("%s" % msg.data)
self.btn.Enable()
#----------------------------------------------------------------------
def VarData(self):
HOST = '127.0.0.1'
USERID = 'test'
PASSWD = '[email protected]'
FILE = r'F:\Programming\temp\Test.zip'
varList = [HOST, USERID, PASSWD, FILE]
FtpValues.Values = HOST, USERID, PASSWD, FILE
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()
繼承和ProgressDialog所遇到的問題對於我來說似乎不同於關於在類之間傳遞變量的問題;我懷疑回答ProgressDialog問題將解決主要問題。你可以給一個最小但可運行的程序,其中ProgressDialog不起作用。 – tom10 2012-01-17 01:10:06
當然...更新後! – Simpleton 2012-01-17 20:57:22