Python中的位置参数问题

时间:2016-12-25 16:04:52

标签: python inheritance

我遇到以下Python代码块的问题:

class Person:
    def __init__(self, firstName, lastName, idNumber):
        self.firstName = firstName
        self.lastName = lastName
        self.idNumber = idNumber
    def printPerson(self):
        print("Name:", self.lastName + ",", self.firstName)
        print("ID:", self.idNumber)

class Student(Person):
        def _init_(self,firstName,lastName,idNum,scores):
            self.scores = scores
            Person.__init__(self, firstName, lastName, idNum)

        def calculate(self):
            s = 0
            for n in self.scores:
                s = s + n
            avg = int(s/len(self.scores))
            if avg >= 90 and avg <= 100:
                return 'O'
            if avg >= 80 and avg <= 90:
                return 'E'
            if avg >= 70 and avg <= 80:
                return 'A'
            if avg >= 55 and avg <= 70:
                return 'P'
            if avg >= 40 and avg <= 55:
                return 'D'
            if avg < 40:
                return 'T'

    line = input().split()
    firstName = line[0]
    lastName = line[1]
    idNum = line[2]
    numScores = int(input()) # not needed for Python
    scores = list( map(int, input().split()) )
    s = Student(firstName, lastName, idNum, scores)
    s.printPerson()
    print("Grade:", s.calculate())

我收到以下错误:

Traceback (most recent call last):
File "solution.py", line 43, in <module>
s = Student(firstName, lastName, idNum, scores)
TypeError: __init__() takes 4 positional arguments but 5 were given

有人可以帮我这个吗?我认为在初始化s类的Students对象时我给出了正确数量的参数。

1 个答案:

答案 0 :(得分:1)

问题是python认为你还没有定义__init__,因为你不小心写了_init_(只有一个下划线)

这段代码应该有所帮助:

class Student(Person):
    def __init__(self,firstName,lastName,idNum,scores): # Changed _init_ to __init__
        self.scores = scores
        Person.__init__(self, firstName, lastName, idNum)

    def calculate(self):
        s = 0
        for n in self.scores:
            s = s + n
        avg = int(s/len(self.scores))
        if avg >= 90 and avg <= 100:
            return 'O'
        if avg >= 80 and avg <= 90:
            return 'E'
        if avg >= 70 and avg <= 80:
            return 'A'
        if avg >= 55 and avg <= 70:
            return 'P'
        if avg >= 40 and avg <= 55:
            return 'D'
        if avg < 40:
            return 'T'