Results 1 to 3 of 3

Thread: [python] multiple files of source code

  1. #1
    Join Date
    Nov 2006
    Location
    Pennsylvania
    Beans
    423

    [python] multiple files of source code

    how do I use multiple files of source code with python?

    Right now I want to begin with one file that contains one class, along with GUI components.

    and have that class initialize an instance of another object that is defined in another file.
    Your Ubuntu User number is # 15355

    A must Read for anyone interested in Computer Programming.

  2. #2
    Join Date
    Mar 2005
    Beans
    947
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: [python] multiple files of source code

    The key is "import".

    Code:
    import yourmodule
    
    newinstance = yourmodule.YourClass()
    or you could say:

    Code:
    from yourmodule import YourClass
    
    newinstance = YourClass()

  3. #3
    Join Date
    Nov 2008
    Location
    /home
    Beans
    289
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: [python] multiple files of source code

    Also there is the "package" solution where you have a folder "Modules" (you can call the folder whatever you want) with several .py files which can all contain 1 or more classes. Inside the Modules folder you put a file called __init__.py (notice double _ before and after) where you import all modules within the folder.

    Folder hiarchy:
    Code:
    Modules
        /Functions.py
        /MyOsRelatedSTuff.py
        /whatever.py
        /__init__.py
    Inside __init__.py

    Code:
    from Functions import *
    import MyOsRelatedSTuff
    import whatever
    Notice that you exclude the .py - then to import this in your main_app.py just:

    Code:
    Import foldername
    In our case

    Code:
    Import Modules
    Then to use a class within Functions you need to call Modules.Functions.YourClass()

    This is a really great way of orginazing your code, although this is probably more used on bigger projects.
    Last edited by Sprut1; December 31st, 2008 at 01:00 AM.
    Desktop: Windows 7 / Ubuntu 10.04
    Laptop-: Vista
    Netbook: Ubuntu 10.04

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •