[英]How to call a method implemented by user from a different class?
我為對象提供了一個指向“ file.py”位置的路徑,我需要從中調用一個名為“ compress”的方法
file.py
def compress(arg):
return arg-5
其他
class Algorithm:
def __init__(self, path):
self.path = path #/PATH/TO/file.py
def func(self, arg1):
return self.path.compress(arg1)
當然,這是一個虛擬的示例,但是如何以正確的方式實現func呢? 可能嗎?
使用importlib模塊,您可以動態加載適當的路徑,然后從該模塊中調用適當的函數! 一個使用os.path
的簡單示例:
import importlib
my_module = importlib.import_module('os.path')
my_module.exists("/non_existing_path")
在這種情況下,您可能需要進行一些其他檢查,例如文件是否存在和函數是否存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.