Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling one method from another within same class in Python

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?

I will illustrate with code.

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 "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?

like image 639
kirti Avatar asked Sep 13 '14 17:09

kirti


1 Answers

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)
like image 96
falsetru Avatar answered Oct 17 '22 19:10

falsetru