2015-04-03 58 views
-2

我试图从一个函数获取输入和另一个函数dispaying,但我无法得到预期的结果蟒蛇访问另一个函数变量错误

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> 

怎么能灌胃等我输入的价值?

回答

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) 
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)