我试图从一个函数获取输入并在另一个函数中显示它但我无法获得预期的结果
class Base(object):
def user_selection(self):
self.usr_input = input("Enter any choice")
user_input = self.usr_input
return user_input
def switch_selection(user_input):
print user_input
b = Base()
b.user_selection()
b.switch_selection()
当我执行这个程序时,我得到了
Enter any choice1
<__main__.Base object at 0x7fd622f1d850>
我应该得到我输入的值,但我得到了
<__main__.Base object at 0x7fd622f1d850>
我怎样才能得到我输入的值?
答案 0 :(得分:1)
def switch_selection(user_input): print user_input .. b.switch_selection()
您可能会注意到在调用它时您没有将任何参数传递给switch_selection
,但您预计会收到一个参数。那里有一种认知脱节。你碰巧实际上收到了一个论点,即b
。 Python中的对象方法接收其对象实例作为其第一个参数。您收到的论点不是user_input
,而是self
。这就是您正在打印的内容,这是您所看到的输出。
解决这个问题的两种可能性:
class Base(object):
def user_selection(self):
self.user_input = input("Enter any choice")
def switch_selection(self):
print self.user_input
或:
class Base(object):
def user_selection(self):
return input("Enter any choice")
def switch_selection(self, user_input):
print user_input
b = Base()
input = b.user_selection()
b.switch_selection(input)
答案 1 :(得分:0)
尝试此代码适合我,
class Base(object):
def user_selection(self):
self.usr_input = input("Enter any choice")
user_input = self.usr_input
return user_input
def switch_selection(self,user_input):
print user_input
b = Base()
g=b.user_selection()
b.switch_selection(g)