61

I was trying to pass a value from one method to another within the class. 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()

The main issue in here is: I cannot call the 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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
kirti
  • 649
  • 1
  • 6
  • 5
  • 3
    For those who've come here from google in search of a canonical dupe: [Python call function within class](//stackoverflow.com/q/5615648) – Aran-Fey Aug 16 '18 at 10:17

1 Answers1

92

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)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • So in the "dropbox_fn", I can use the "filename" directly rather than "self.name=filename"????? – kirti Sep 13 '14 at 17:37
  • 1
    ok it worked!!. the "dropbox_fn" successfully got the filename from "on_any_event". – kirti Sep 13 '14 at 17:43