Where to save classes? How to access classes?

D

David Mitchell

Hi,

I'm trying to get into the object oriented aspect of Python. If I create
a custom class (in it's own file), how do I access that class in a
function in a different file? In Java there's the notion of a CLASSPATH,
where you can tell the compiler to look for classes. Is there something
similar to this in Python?

Thanks,

Dave
 
D

David Wahler

David said:
Hi,

I'm trying to get into the object oriented aspect of Python. If I create
a custom class (in it's own file), how do I access that class in a
function in a different file? In Java there's the notion of a CLASSPATH,
where you can tell the compiler to look for classes. Is there something
similar to this in Python?

Thanks,

Dave

Python is a little different than Java in this respect. Whereas Java
loads code one public class at a time, Python loads it in modules,
where a module is (generally speaking) one source file.

Say you have a file, foo.py:
###############################
class Xyz:
def do_stuff(self):
pass

class Abc:
def do_more_stuff(self):
pass
###############################

Then in another file, inserting the statement "import foo" will execute
foo.py and make its global variables available as part of an object
called "foo". There is no automatic loading by class and package name
like Java does it. Once you've done this, you can access the members
using expressions such as "foo.Xyz" e.g. "foo.Xyz().do_stuff()".

As for the search path: sys.path (the path attribute of the sys module)
is a list of directories which are searched, in order, for modules
specified by "import". By default this is the current directory
followed by a few standard Python library directories; most of the time
you shouldn't need to change it, at least for simple projects.

Hope this helps,

-- David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top