[英]Calling one method from another within same class in Python
I am very new to python.我对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".因为在我的代码中,“if”正在调用类的方法“on_any_event”,作为回报,它应该调用我的另一个方法“dropbox_fn”,它使用来自“on_any_event”的值。 Will it work, if the "dropbox_fn" method is outside the class?如果“dropbox_fn”方法在类之外,它会起作用吗?
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.这里的主要问题是......我不能在没有事件参数的情况下调用“on_any_event”方法。 So rather than returning value, calling "dropbox_fn" inside "on_any_event" would be a better way.因此,与其返回值,不如在“on_any_event”中调用“dropbox_fn”是更好的方法。 Can someone help with this?有人可以帮忙吗?
To call the method, you need to qualify function with self.
要调用该方法,您需要使用self.
限定函数self.
. . In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).除此之外,如果要传递文件名,请添加filename
参数(或您想要的其他名称)。
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)
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.从一个范围到另一个范围访问成员函数或变量(在你的情况下,一个方法到另一个方法,我们需要用类对象引用方法或变量。你可以通过引用作为类对象的 self 关键字来实现。
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.