【问题标题】:getting two classes to interact让两个类进行交互
【发布时间】:2011-10-11 10:18:12
【问题描述】:

我无法让两个班级互动。这是我要导入文件 youtest.py 的第一个类的代码:

from youtest import MyTest   

class RunIt(object):

  def __init__(self):
    self.__class__ = MyTest

r = RunIt()
r.iffit()

我正在尝试通过此类运行 MyTest 类(代码如下):

from sys import exit

class MyTest(object):

  def death(self):
    exit

  def iffit(self):

    oh_no = raw_input(">")

  print "What is your name?"

  if oh_no == "john":
    print "welcome john"

  else:
    print "game over"
    return 'death'

当我运行它时,我得到以下信息:

文件“youtest.py”,第 19 行 返回“死亡” SyntaxError: 'return' 外部函数

希望这个问题足够清楚,感谢您的帮助。

【问题讨论】:

  • 在我查看了您在 SO 的所有问题后,我强烈建议您阅读the tutorial

标签: python class call return interaction


【解决方案1】:

print "What is your name?" 开始的行没有正确缩进。在 python 中,空格很重要。

【讨论】:

    【解决方案2】:

    在 Python 中,这不是子类化的方式。

    from youtest import MyTest   
    
    class RunIt(MyTest): pass
    
    r = RunIt()
    r.iffit()
    

    虽然在这个例子中r = MyTest() 可以正常工作。

    您的SyntaxError 是由您滥用空白触发的。每个缩进级别使用四个空格,这在 Python 中是标准的,因此您可以清楚地看到事物的组织。

    你还有一个问题:return 'death' 不会调用death,如果你想要的话,你需要return death()

    最后,death() 不会对exit 做任何事情,只是引用它。你需要做exit()

    【讨论】:

      猜你喜欢
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2014-12-24
      • 1970-01-01
      • 2010-10-22
      • 2016-07-05
      • 2016-09-11
      相关资源
      最近更新 更多