emufossum13
emufossum13

Reputation: 407

Importing functions from classes outside original file

I'm working on a text based adventure game. One of the things that I want to do, is build the game using classes, have the main data classes in a separate file, and then have the actual main loop that calls all the classes and functions, in a separate file. This is what I have so far my main loop in calling the main classes file

import time
import sys
import pickle
import className

playerPrefs.createNew()

and here is the part of the code in the main classes file that is affected when I run the program.

class playerPrefs(object):
# This line will create a function to create a new player name
def createNew(self):
    print "Welcome to Flight of Doom Character Creation Screen."
    time.sleep(2)
    print "Please type your first and last Name, spaced in between, at the prompt"
    time.sleep(2)

My problem comes when I try to run the createNew function from my main game file. As you can see, I import className which is the name of the file with the classes in it. That file is located in the same location my main game file is located. I suspect it may have something to with constructors, but I'm not sure. If you guys could help me, I would very much appreciate it.

Btw, this isn't a ploy to try and get you guys to answer my question :) I just wanted to say that this site and the programming wizards on here, have saved my butt many times. Thanks guys for being apart of this community project.

Upvotes: 1

Views: 107

Answers (3)

Blender
Blender

Reputation: 298126

Because your createNew method takes a self parameter, it's an instance method. It requires an instance of your class in order to be called. Now there are two ways of solving this problem:

  1. Make an instance of the class:

    playerPrefs().createNew()
    
  2. Make the method a static method:

    class playerPrefs(object):
        @staticmethod
        def createNew():
            print "Welcome to Flight of Doom Character Creation Screen."
            time.sleep(2)
            print "Please type your first and last Name, spaced in between, at the prompt"
            time.sleep(2)
    

Neither of these seem appropriate here given your structure, as the whole class seems a little useless from what I can tell.

Upvotes: 0

Crowman
Crowman

Reputation: 25908

You've defined playerPrefs() as an instance method, rather than a class method (since it has self as its first argument). Therefore, you need to create an instance before you call it, e.g.:

p = playerPrefs()
p.createNew()

Also, your code as written shouldn't run at all, since you haven't indented the definition of createNew(), and you need to.

As Vedran says, either use:

p = className.playerPrefs()

to make it work, or import playerPrefs from className as he suggests.

Upvotes: 1

Vedran Šego
Vedran Šego

Reputation: 3765

Try

from className import *

or

from className import playerPrefs

Upvotes: 0

Related Questions