经过几天的搜索和尝试不同的代码,我仍然无法弄清楚我的问题。因此,我在这里发布了这个问题。
对于这个问题,我使用的是 Python 2.7.2 具体来说,我正在使用组合将一个类的功能导入另一个类。导入类的函数包括一个基于 raw_input 的简单 if 语句。根据用户的输入,if 语句应该以某种方式调用或至少帮助调用与输入对应的新函数。但是,此函数将在正在导入的类的一部分中,而不是在导入的类中。
我在这里使用了两个 .py 文件,每个类一个,它们位于同一个文件夹中。
这是第一个文件 (main.py),其中包含主类:
# importing class from file in same folder
from class_decision import Decision
class Main_Compositor(object):
def __init__(self):
# using composition to call the function of the imported class
self.door_decision = Decision()
def comp_door(self):
self.door_decision.user_text()
if door == "left":
left_door()
elif door == "right":
right_door()
else:
print "incorrect input"
def left_door(self):
print "you're in the left room"
def right_door(self):
print "you're in the right room"
# instantiating
A_Compositor = Main_Compositor()
# calling A_Compositor's function comp_door()
A_Compositor.comp_door()
这里是 class_decision.py 文件,正在导入其类:
class Decision(object):
def user_text(self):
print "which door do you open:"
print "left or right?"
door = raw_input("> ")
if door == "left":
print "you have chosen the left door"
return door
elif door == "right":
print "you have chosen the right door"
return door
else:
print "you must choose a door"
self.user_text()
如您所见,我正在尝试使用 Return 让主类知道变量 door。这可能是对 Return 的错误使用。我也试过玩弄 getattr 但没有成功。如果这个问题被问了很多,我深表歉意。和我类似的问题似乎都与数组有关,我无法通过他们的答案真正弄清楚我的问题。感谢您的帮助。
请您参考如下方法:
def user_text(self):
print "which door do you open:"
print "left or right?"
door = raw_input("> ")
if door == "left":
print "you have chosen the left door"
return door
elif door == "right":
print "you have chosen the right door"
return door
else:
print "you must choose a door"
return self.user_text() # don't forget to return in the recursion case
def comp_door(self):
choice = self.door_decision.user_text() # actually use the returned result
if choice == "left":
self.left_door()
elif choice == "right":
self.right_door()
else:
print "incorrect input"
