Python中的函数列表作为多个对象读取

时间:2016-09-25 04:55:25

标签: python

我有一个看起来像这样的函数:

class Question:
    Ans = "";
    checkAns = 0;
    isPos=False;
    def Ask(Q, PosAns):
        checkAns=0;
        Ans = raw_input("{} ({})".format(Q,PosAns));
        while(checkAns<len(PosAns) and isPos!=True):
            if(Ans==PosAns[x]):
                isPos=True; #if it IS a possible answer, the loop ends
            checkAns+=1;
            if(checkAns==len(PosAns)):
#If the loop goes through all the possible answers and still doesn't find a
#match, it asks again and resets checkAns to zero.
                Ans = raw_input("{} ({})".format(Q,PosAns));
                checkAns=0;
        return ("Good Answer");

ques = Question();
print(ques.Ask("Do you like to code?",["Yes","No"]));

首先,这个函数的要点是接受一个问题(Q)和所有可能的答案(PosAns),如果用户输入的内容不是可能的答案之一,那么该函数将简单再问一遍。

然而,每当我运行它时,它会说Ask()函数只能处理两个参数并且我已经给它三个(注意YesNo里面有两个字符串)。为什么它会读取列表的对象而不是将列表作为参数?如何将列表作为参数?

我确实认识到我编码的方式对于大多数人来说是迂回的和奇怪的,但它只是对我有意义的方式。我对问题的答案比对编写整个函数的新方法更感兴趣(我还在努力)。

1 个答案:

答案 0 :(得分:0)

你错过了自我&#39;在方法声明中。每个类方法(静态方法除外)都要求第一个参数为self。 self被隐含地传递,因此不会出现在我们的方法调用中。 在此示例中,self可用于引用其他调用属性,如isPoscheckAnsans变量

虽然有一点我想知道x这里是什么 if (Ans == PosAns[x])

class Question:
Ans = "";
checkAns = 0;
isPos = False;

def Ask(self, Q, PosAns):
    Ans = raw_input("{} ({})".format(Q, PosAns));
    while (self.checkAns < len(PosAns) and self.isPos != True):
        if (Ans == PosAns[x]):
            isPos = True;  # if it IS a possible answer, the loop ends
        self.checkAns += 1;
        if (self.checkAns == len(PosAns)):
            # If the loop goes through all the possible answers and still doesn't find a
            # match, it asks again and resets checkAns to zero.
            self.Ans = raw_input("{} ({})".format(Q, PosAns));
            self.checkAns = 0;
    return ("Good Answer");