Skip to content Skip to sidebar Skip to footer

Import Class Without Executing .py It Is In?

I defined a class called Prof in a script called AddPntCode90_27.py. It opens some files, does some math, creates output files and so. Now I want to re-use the class for another pr

Solution 1:

The way to do what you want is to use an if __name__ == "__main__" block. See this question.

It's perfectly fine to define classes in scripts, but you cannot import the class without executing the script, because it is only by executing the script that you define the class. Class definitions are not a "compile-time declaration" in Python; they are executed in order just like everything else in the module. You should use an if __name__=="__main__" block to protect code that you don't want to be run when you import your file as a module.

Solution 2:

You should the if __name__="__main__: idiom to check whether Python is running the code or the code is being imported as a module.

Post a Comment for "Import Class Without Executing .py It Is In?"