Importing Class from Another File

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How to import the class within the same directory or sub directory?

Python 2

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".

Then just do...

from user import User
from dir import Dir

The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.

bin/
main.py
classes/
user.py
dir.py

So if the directory was named "classes", then you'd do this:

from classes.user import User
from classes.dir import Dir

Python 3

Same as previous, but prefix the module name with a . if not using a subdirectory:

from .user import User
from .dir import Dir

How to import a class from another file in python?

If you're using Python 3, then imports are absolute by default. This means that import example will look for an absolute package named example, somewhere in the module search path.

So instead, you probably want a relative import. This is useful when you want to import a module that is relative the module doing the importing. In this case:

from ..example.ClassExample import ClassExample

I'm assuming that your folders are Python packages, meaning that they contain __init__.py files. So your directory structure would look like this.

src
|-- __init__.py
|-- example
| |-- __init__.py
| |-- ClassExample.py
|-- test
| |-- __init__.py
| |-- ClassExampleTest.py

Import class from another file, but element name is not defined (executable example)

The basic problem is that you have not created a reference to the attribute.
First of all, care should be taken to prefix all attributes inside a new object (class Page1 __init__) with self. in front of all attributes.
This makes the value part of the object and
can be called after the initialization.
In your case, the entire class could be passed as an argument to External.

class Page1(tk.Frame):
def __init__(self, master, **kw):
super().__init__(master, **kw)
...
self.select_only_way = select_tricket.split('>>>')[0]
...
def click():
k = external_class.External(self)
...
class External:
def __init__(self, Page1): # added textbox argument
...
self.cursor.execute('SELECT a, b FROM other WHERE a =?', [Page1.select_only_way])
...
if (self.element and self.element[0] == "try1"):
Page1.textbox.insert("end", "ok")
...

How can i import class from another file in python?

That is circular depency. Create one more file, for example database.py where you import your cursor.

# database.py
conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='python')
cursor=conn.cursor()

# alloweds.py
from database import cursor
...

# access.py
from alloweds import clasifier, record_user
from database import cursor
...

importing class from another file gives error when working and no error when not working

You should move the package folder to a directory that is already in PATH

export PYTHONPATH="${PYTHONPATH}:B:\Programming\Python\RaceDash\src\
python3 Main.py

Python - Error importing class from another file

Python paths can get kind of tricky. I don't claim that this is the best approach, but it's what I hacked together on my lunch. Perhaps it can get you where you need to go.

When you run main.py, you're in the internal/ directory. You need to go up a level and then access the user/ directory. That's what happens with sys.path.append('../'). The module usermanager.py is in the user/ directory, so to import from user.py, we want to point to the current directory. Hence the period in from .user import User.

Here's the directory structure I used. I believe it is the same as what you have.

C:.
├───internal
│ main.py
│ __init__.py

└───user
│ models.py
│ user.py
│ usermanager.py
└───__init__.py

__init__.py

The __init__.py files are empty. Their presence indicates to Python that the directories are modules1.

main.py

import sys
sys.path.append('../')

from user import user
from user import usermanager
from user import models

my_user = user.User()
my_user.message()

my_user_manager = usermanager.UserManager()
my_user_manager.message()
my_user_manager.CreateUser()

my_model = models.Model()
my_model.message()

models.py

class Model():

def message(self):
print("This is a Model!")

user.py

class User():

def message(self):
print("This is a User!")

usermanager.py

from .user import User

class UserManager():

def message(self):
print("This is a UserManager!")

def CreateUser(self):
new_user = User()
print("I created the user: ", new_user)

Now, when I call main.py I get:

c:\project\internal>python main.py
This is a User!
This is a UserManager!
I created the user: <user.user.User object at 0x0000000002A61EB8>
This is a Model!

Everyone is talking to everyone else. Hopefully you can extrapolate that to your use case! If not, Chris Yeh has an article "The Definitive Guide to Python import Statements" you may find helpful.


1 See What is __init__.py for? to learn more about how that works.

Python import class from another class

I believe the correct syntax is to import the top-level class, then call the nested class through the top level class.

from fileno1 import MyClass

print(MyClass.MySecondClass.value)

There's a guide on nested classes here that you might find useful.



Related Topics



Leave a reply



Submit