Find the answer to your Linux question:
Results 1 to 2 of 2
Hey guys, i just started learning python (i usually use java/C). this has got me stumped as its not mentioned in the documentation (unless im skimming it every time). How ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Sep 2005
    Posts
    6

    Python - instanciating classes from other files


    Hey guys, i just started learning python (i usually use java/C).

    this has got me stumped as its not mentioned in the documentation (unless im skimming it every time).

    How does one instanciate a class from another file

    i thought it would be
    -----------------------------------code---------------------------
    import file.py

    thisFile = ClassName()
    -------------------------------not code---------------------------
    but its not

    and its not
    -----------------------------------code---------------------------
    thisFile= filename.ClassName()
    -------------------------------not code---------------------------
    im stuck

    cheers
    dave

  2. #2
    Linux User
    Join Date
    Jul 2004
    Location
    Poland
    Posts
    368
    Suppose you have a file called foo.py with class Foo in it (i'm not sure if file is a good name for your module, as it clashes with built-in function file):

    Code:
    class Foo:
      def __init__(self, x):
        self.x = x
        print 'Foo constructed with x =', x
    You can now import the entire file:
    Code:
    import foo
    my_object = foo.Foo(42)
    (First note that you omit .py file extension in import statement)

    This way you'll have to prefix all symbols from foo.py module with foo dot as above.

    Another option is to import a single symbol:
    Code:
    from foo import Foo
    my_object = Foo(42)
    Here, "foo.Foo(42)" wouldn't work, because you imported only Foo. A convenient shortcut is to import all symbols from a module:

    Code:
    from foo import *
    my_object = Foo(42)
    Which is similar to the previous solution but imports everything (well, almost).

    Hope this helps. (and yes, you are skimming it every time: http://docs.python.org/tut/node8.html)
    "I don't know what I'm running from
    And I don't know where I'm running to
    There's something deep and strange inside of me I see"

Posting Permissions

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