問題描述
我對 python 很陌生.我試圖在類中將值從一種方法傳遞給另一種方法.我搜索了這個問題,但我無法得到正確的解決方案.因為在我的代碼中,if"正在調用類的方法on_any_event",作為回報應該調用我的另一個方法dropbox_fn",該方法利用on_any_event"中的值.如果dropbox_fn"方法在類外,它會起作用嗎?
I am very new to python. I was trying to pass value from one method to another within the class. I searched about the issue but i could not get proper solution. Because in my code, "if" is calling class's method "on_any_event" that in return should call my another method "dropbox_fn", which make use of the value from "on_any_event". Will it work, if the "dropbox_fn" method is outside the class?
我會用代碼來說明.
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath=event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
#print srcpath.split(' ', 12 );
filename=srcpath[12:]
return filename # I tried to call the method. showed error like not callable
def dropbox_fn(self)# Or will it work if this methos is outside the class ?
#this method uses "filename"
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else '.'
print ("entry")
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
這里的主要問題是.. 我不能在沒有事件參數的情況下調用on_any_event"方法.因此,與其返回值,不如在on_any_event"中調用dropbox_fn"是一種更好的方法.有人可以幫忙嗎?
The main issue in here is.. I cannot call "on_any_event" method without event parameter. So rather than returning value, calling "dropbox_fn" inside "on_any_event" would be a better way. Can someone help with this?
推薦答案
要調用該方法,您需要使用 self.
限定函數.除此之外,如果要傳遞文件名,請添加 filename
參數(或您想要的其他名稱).
To call the method, you need to qualify function with self.
. In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----
def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)
這篇關于在 Python 中從同一類中的另一個調用一個方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!