Please help me figure it out. With a few questions.

Task one:

I have two files: C: \ pytest \ One \ main.py C: \ pytest \ One \ mymodule.py

mymodule.py contains:

class example: def hello(): print('Hello, world!') def fib(n): a = b = 1 for i in range(n - 2): a, b = b, a + b return b 

main.py contains:

 import mymodule mymodule.example.hello() print(mymodule.example.fib(10)) 

In this case, I imported the entire module. Can I call to import only a class or a function?

 from mymodule import example 

or

 from mymodule import hello 

An error occurs:

 ImportError: cannot import name 'fib' 

Task two: The files are the same, but they are in a different folder. I have two files: C: \ pytest \ One \ main.py C: \ pytest \ Two \ mymodule.py

How to import a file / class or function?

  • about __init__ not forgotten? - titov_andrei
  • I would be very grateful if you explain. I ran into programming only a week ago. - Humornoy
  • In your code, I hope, indentation is not the same as in your example? You after all read about indents in python ? - approximatenumber
  • Yes, I read. I apologize, I forgot to format it when publishing the code. Now corrected. Code mymodule.py is executed - Humornoy
  • one
    1. I did not have an error. In python, methods traditionally write self as the first argument, if you want to statically call methods (like you), then decorator @staticmethod - gil9red add def declarations of the method

1 answer 1

You do not have enough __init_.py File in your C:\pytest\One\ directory to import packages correctly:

  __init_.py main.py mymodule.py 
  • Thanks, the problem was exactly that. I created the usual folder instead of the python package. After I created the package, init .py was generated in it and the modules began to be imported. - Humornoy