NameError: global name 'myExample2' is not defined # modules

后端 未结 5 1535
栀梦
栀梦 2021-01-12 03:48

Here is my example.py file:

from myimport import *
def main():
    myimport2 = myimport(10)
    myimport2.myExample() 

if __name__ == \"__main_         


        
5条回答
  •  执念已碎
    2021-01-12 04:09

    While the other answers are correct, I wonder if there is really a need for myExample2() being a method. You could as well implement it standalone:

    def myExample2(num):
        return num*num
    
    class myClass:
        def __init__(self, number):
            self.number = number
        def myExample(self):
            result = myExample2(self.number) - self.number
            print(result)
    

    Or, if you want to keep your namespace clean, implement it as a method, but as it doesn't need self, as a @staticmethod:

    def myExample2(num):
        return num*num
    
    class myClass:
        def __init__(self, number):
            self.number = number
        def myExample(self):
            result = self.myExample2(self.number) - self.number
            print(result)
        @staticmethod
        def myExample2(num):
            return num*num
    

提交回复
热议问题