Hello,

I am an experienced programmer in OO langauges such as C++, C#, Java... etc.

The problem I have is that I have written a class, and when I try to instantiate that class from another object, the compiler says that it cannot find it at the Import stage. From previouse experience with other languages, as long as the class file is in the same directory it can find it, is python different, do I have to stick the class file somewhere else?

Thank you in advance.

class MyClass1:
        aVariable = 1
import MyClass1:

class MyClass2:

        anObject = new MyClass1()

have you added the path in which Class1 is situated to sys.path?

Try this:

import sys
sys.path.append(place where myclass1 is located)
import MyClass1

class MyClass2():
    anobject = MyClass1()

Make sure the file in which MyClass1 is located is called MyClass1.py or pyw or something like that

You don't use colons or semicolons in Python, normally.

Only use colons for:
if
else
elif
def
class
for
while

And similar. Do not use a colon for import.

Thanks paulthom12345, that worked.

If MyClass1.py is in the working directory, you shouldn't need to worry, since the first entry in PYTHONPATH is the present directory. Your problem is the
import MyClass1:
Python now looks for the file MyClass1:.py and of course can't find it.

Want to take a look at PYTHONPATH? Here it is:

# show the system path for Python = PYTHONPATH

import sys
print sys.path
print
print "The present working directory:"
print sys.path[0]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.