简体   繁体   中英

Python - Cannot call a function from a py file within a class?

I am trying to call Myfunction from a py script and this happens in a Class. But I got an error saying Myfunction is not defined. How do I avoid this? I know I can put everything within file_that_contains_Myfunction_versionA(B).py into a class and call it in main() . But is there other way to do it?

The trick here is that the name of the function is the same and I can't import the script at the very beginning since I don't know the condition until I run Myclass() .

class Myclass():
    def __init__(self):
        self.main()

    def main(self):
            if conditionA:
                exec(open("./file_that_contains_Myfunction_versionA.py").read())
                Myfunction()
            if conditionB:
                exec(open("./file_that_contains_Myfunction_versionB.py").read())
                Myfunction()

Did you import the other script into the one you're calling it from?

from otherscript import function_A

function_A()

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