getting two classes to interact
I am having trouble getting two classes to interact. Here is the code for the first class where i am importing file youtest.py:
from youtest import MyTest
class RunIt(object):
def __init__(self):
self.__class__ = MyTest
r = RunIt()
r.iffit()
I am trying to run class MyTest through this class (code below):
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'
when i run this i get the following:
File "youtest.py", line 19 return 'death' SyntaxError: 'return' outside function
Hope this question is clear开发者_如何学C enough thanks for the help.
The lines starting from print "What is your name?"
are not indented properly. In python the whitespace is significant.
In Python, this isn't how to subclass.
from youtest import MyTest
class RunIt(MyTest): pass
r = RunIt()
r.iffit()
Although in this example r = MyTest()
would work fine.
Your SyntaxError
is triggered by your misuse of white space. Use four spaces for each indentation level, as is standard in Python, so you can clearly see the organization of things.
You have another problem: return 'death'
will not call death
, you need to return death()
if that's what you want.
Finally, death()
will not do anything with exit
, just reference it. You need to do exit()
.
精彩评论