python - 如何从不同的文件调用方法而不在python中导入它

  1. MainLibrary.py - 所有重要的方法都在这个文件中可用
  2. SecondaryLibrary.py - 此文件中提供了特定方法,不能放在 MainLibrary.py 文件中

有些旧脚本只导入 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.
    

最佳答案

您可以在脚本中构造一个类来执行您需要的操作;

# 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

https://stackoverflow.com/questions/62636099/

相关文章:

amazon-web-services - server.servlet.context-path

flutter - 如何解决 PlatformException (PlatformExceptio

python - 如何在 Tkinter 窗口上使用 for 循环创建多个框架?

reactjs - 如何使用 react-email-editor 加载 HTML 模板而不是 js

swift - 达到最大时间戳计数,不会记录更多事件 Xcode

c - 尝试在 bmp 文件中画线时如何在 C 中实现 Bresenham 的线算法?

r - 控制 geom_line() 图表中的日期(x 轴)间隔

c# - EF 核心错误 : "Comparison on entity type is not s

asp.net - 如何为网络浏览器的用户获取 AD 属性

google-chrome - 报告 api : Is there a way to debug w