By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,908 Members | 1,892 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,908 IT Pros & Developers. It's quick & easy.

Where to save classes? How to access classes?

P: n/a
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
Nov 1 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

David Mitchell wrote:
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

Nov 1 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.