Calling one method from another within same class in Python(在 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)
这篇关于在 Python 中从同一类中的另一个调用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中从同一类中的另一个调用一个方法
基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01