Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    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

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

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


  2. #2
    Linux User
    Join Date
    Jul 2004
    Suppose you have a file called 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):

    class Foo:
      def __init__(self, x):
        self.x = x
        print 'Foo constructed with x =', x
    You can now import the entire file:
    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 module with foo dot as above.

    Another option is to import a single symbol:
    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:

    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:
    "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