我需要一个reservation
函数来调用类的相应方法。
但是如果我必须在类之外提供用户输入,我怎么能将参数传递给方法呢?
class Stay:
def __init__(self):
self._type_room= ''
def set_type_room (self, NewRoom):
NewRoom= select_room()
self._type_room= NewRoom
def select_room():
Newroom= input ('insert')
if NewRoom == 'Single':
print ('ok')
else:
print ('only Single')
return NewRoom
def reservation ():
stay= Stay()
stay.set_type_room(NewRoom)
答案 0 :(得分:0)
NewRoom
未在函数reservation
内或全局范围内定义(不存在),因此您无法访问它。
当您通过set_type_room
函数重新创建参数时,您将不必要地将参数传递给select_room
。
所以,你可以删除那个参数,你应该没问题:
class Stay:
def __init__(self):
self._type_room= ''
def set_type_room (self):
self._type_room = select_room()
def select_room():
Newroom= input ('insert')
if NewRoom == 'Single':
print ('ok')
else:
print ('only Single')
return NewRoom
def reservation ():
stay= Stay()
stay.set_type_room()
如果您希望set_type_room
成为设置方法:
class Stay:
def __init__(self):
self._type_room= ''
def set_type_room (self, NewRoom):
self._type_room = NewRoom
def select_room(stay):
NewRoom = input ('insert')
if NewRoom == 'Single':
print ('ok')
else:
print ('only Single')
stay.set_type_room(NewRoom)
def reservation ():
stay = Stay()
select_room(stay)