【发布时间】:2012-10-21 12:13:46
【问题描述】:
经过几天的搜索和尝试不同的代码,我仍然无法找出我的问题。因此,我在这里发布了这个问题。
对于这个问题,我使用的是 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,但没有成功。如果这个问题被问了很多,我很抱歉。我的类似问题似乎都与数组有关,我无法通过他们的回答真正找出我的问题。感谢您的帮助。
【问题讨论】:
-
您的最后一个
self.user_text()应该是return self.user_text()。要解决您的问题,我认为您可以使用door = self.door_decision.user_text()。 -
谢谢,搅拌机。这似乎可以解决问题。
-
作为一个次要的挑剔,您可能不应该调用实例
A_Compositor,因为在其他任何地方您都遵循标题大写用于类,小写用于变量的命名约定。 -
哦,好吧。我想既然
A_Compositor是一个类的实例,它也应该有类得到的大写字母。 -
不,类实例是变量,就像整数一样。 (实际上,它有点复杂——变量只是名称,任何名称都可以包含整数、类实例,甚至是类本身……但你可能还不想学。)
标签: python function python-2.7 return