python 访问另一个函数变量错误
python accessing another function variable error
我正在尝试从一个函数获取输入并将其显示在另一个函数中,但我无法获得预期的结果
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>
如何获取输入的值?
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)
试试这个非常适合我的代码,
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)
我正在尝试从一个函数获取输入并将其显示在另一个函数中,但我无法获得预期的结果
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>
如何获取输入的值?
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)
试试这个非常适合我的代码,
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)