【问题标题】:Importing functions from classes outside original file从原始文件之外的类中导入函数
【发布时间】:2013-06-16 21:24:23
【问题描述】:

我正在开发一款基于文本的冒险游戏。我想做的一件事是使用类构建游戏,将主数据类放在一个单独的文件中,然后将调用所有类和函数的实际主循环放在一个单独的文件中。到目前为止,这就是我调用主类文件的主要循环

import time
import sys
import pickle
import className

playerPrefs.createNew()

这是我运行程序时受影响的主类文件中的代码部分。

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)

当我尝试从我的主游戏文件运行 createNew 函数时,我的问题出现了。如您所见,我导入了 className,它是其中包含类的文件的名称。该文件位于我的主游戏文件所在的同一位置。我怀疑它可能与构造函数有关,但我不确定。如果你们能帮助我,我将不胜感激。

顺便说一句,这不是试图让你们回答我的问题的策略:) 我只想说这个网站和这里的编程向导已经救了我很多次。感谢大家参与这个社区项目。

【问题讨论】:

    标签: python class function object


    【解决方案1】:

    您已将playerPrefs() 定义为实例方法,而不是类方法(因为它的第一个参数是self)。因此,您需要在调用它之前创建一个实例,例如:

    p = playerPrefs()
    p.createNew()
    

    此外,您编写的代码根本不应该运行,因为您没有缩进 createNew() 的定义,而您需要缩进。

    正如 Vedran 所说,要么使用:

    p = className.playerPrefs()
    

    让它工作,或者按照他的建议从className 导入playerPrefs

    【讨论】:

      【解决方案2】:

      试试

      from className import *
      

      from className import playerPrefs
      

      【讨论】:

        【解决方案3】:

        因为您的createNew 方法采用self 参数,所以它是一个实例方法。它需要您的类的实例才能被调用。现在有两种方法可以解决这个问题:

        1. 创建一个类的实例:

          playerPrefs().createNew()
          
        2. 使方法成为静态方法:

          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)
          

        考虑到你的结构,这些似乎都不合适,因为据我所知,整个班级似乎有点没用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-11
          • 1970-01-01
          • 2019-04-12
          • 2011-10-09
          • 1970-01-01
          • 1970-01-01
          • 2015-04-29
          • 1970-01-01
          相关资源
          最近更新 更多