简体   繁体   中英

How to call a method from a different file without importing it in python

  1. MainLibrary.py - All the important methods are available in this file
  2. SecondaryLibrary.py - specific methods are available in this file, which cannot be placed in the MainLibrary.py file

There are old scripts which only imports the MainLibrary and does not import the SecondayLibrary file. Here, when these old scripts are called - instead of accessing the methods from the mainlibrary file, is it possible to access the methods from the secondaryLibrary file without changing anything in the scripts or MainLibrary file.

Example:

MainLibrary.py file:

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 file

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"""

    

"The old scripts will recieve the values for paramters "a and b" and C will be always 0" But, with the new requirements, i need to compute the value of C based on the values of a and b - all the computation part are handled in xy method"

Note: I dont have permission to edit the MainLibrary file or the Scripts, everything has to be handled in the SecondaryLibrary file

Script:

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.
    

You can construct a class in your script to do what you require;

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM