在 Python 中从同一类中的另一个调用一个方法

问题描述

我对 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)

相关文章