0

I had a class in as below in module practice. practice/example.py

class Example :

    #some code#

e1= Example();
e2= Example();

and I had practice/__init__.py

from example import Example

and i had main.py

import sys , python_practice


e3 = python_practice.Example();


from python_practice import *

e1.sum(1,2);

but i am getting error as

Traceback (most recent call last):
File "practice.py", line 11, in <module>
e1.sum(1,2);
NameError: name 'e1' is not defined

Where I went wrong....

Is it possible to import the object of the class to another module ?

0

2 Answers 2

4

Yes, you just have to import it.

When you do from python_practice import *, you get everything defined in practice/__init__.py. In that __init__.py, you don't import e1, so you don't import it with from python_practice import * either.

If you want e1 to be available at the top level python_practice, you need to import it in __init__.py. Change your code there to from example import Example, e1, e2.

Sign up to request clarification or add additional context in comments.

4 Comments

If suppose i didn't had init.py in the python_practice module how can i import the object ? Is there any other way of doing it.
If you don't have __init__.py you don't have a package at all, so you can't import it at all. If you had the practice directory directly on the path, you could import it with from example import Example, e1, e2, but it probably would not be a good idea to create a top-level package named example.
Hello BrenBarn..... Thank you for the help. Now i had a different issue. I wnat some help. In the above exaple i know the instance of the class as e1 or e2. But in my application i am managed to get the object name as string. with that string how can i will be able to access the object.
@mkreddy: You should ask that as a separate question.
2

__init__ sets up the namespace for your package. Since __init__ imports Example, then Example is available in the package namespace (e.g. python_practice.Example). e1 is not available there because nothing you did in __init__ makes e1 available there.

Of course, you can pretty much always get there ...

from python_practice.example import e1

should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.