[英]How to call a method from a different file without importing it in python
有些旧脚本只导入 MainLibrary,不导入 SecondayLibrary 文件。 在这里,当调用这些旧脚本时 - 不是从 mainlibrary 文件访问方法,而是可以从 secondaryLibrary 文件访问方法而不更改脚本或 MainLibrary 文件中的任何内容。
例子:
MainLibrary.py 文件:
class MainLibrary:
def x(self, a =0, b=0, c= 0):
""" Do some operation with these values"""
def y(self, a=0,b=0,c=0):
"""Do some operation with these values"""
SecondaryLibrary.py 文件
class SecondaryLibrary:
def xy(self, a=0, b=0, c=0):
"""Compute the value of C based on the values of a and b and then do some operation"""
“旧脚本将接收参数“a 和 b”的值,而 C 将始终为 0” 但是,根据新要求,我需要根据 a 和 b 的值计算 C 的值 - 所有计算部分以 xy 方法处理"
注意:我无权编辑 MainLibrary 文件或脚本,一切都必须在 SecondaryLibrary 文件中处理
脚本:
from MainLibrary import *
obj = MainLibrary()
"get the values of a and b"
obj.x(a,b)
Here when method X is called --> i need to call method "xy" from the sceondaryLibrary file.
您可以在脚本中构造一个 class 来执行您的要求;
# MainLibrary.cs
class MainLibrary(object):
def x(self, a, b, c):
return a + b + c
def y(self, a, b, c):
return a * b * c
# SecondaryLibrary.cs
class SecondaryLibrary(object):
def xy(self, a, b,c ):
return c - a - b
# Script.cs
from MainLibraryimport MainLibrary
from SecondaryLibrary import SecondaryLibrary
class Script(MainLibrary, SecondaryLibrary):
def x(self, a, b, c):
# As in your question this is how we specify that calling
# obj.x should return the result of .xy
return super().xy(a, b, c)
def y(self, a, b, c):
return super().y(a, b, c)
if __name__ == '__main__':
obj = Script()
result = obj.x(1, 2, 5)
print(result) # gives 5 - 2 - 1 => 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.