如何在外部函数中调用方法

时间:2016-07-05 10:55:54

标签: python python-3.x oop

我需要一个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)

1 个答案:

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