教授对Python作业的回答将无法运行:TypeError:__init __()缺少1个必需的位置参数:'gender'

时间:2019-12-10 23:54:55

标签: oop python-3.6

我确定之前已经有人问过这个问题,但是目前我还不能理解其他问题是如何回答我的。有人可以用此代码解释问题吗?我看不到:

{ node: { title: 'Default Title' } }

PyCharm返回的错误是:

class Person:
    name = ''
    age = 0
    gender = ''

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender


class Employee(Person):
    title = ''
    salary = 0

    def __init__(self, name, age, gender, title, salary):
        Person.__init__(name, age, gender)
        self.title = title
        self.salary = salary


George = Employee("George", 30, "Male", "Manager", 50000)
print("George's info is: Name is %s, Age is %d, Gender is %s, Title is %s, and Salary is %d" % (
George.name, George.age, George.gender, George.title, George.salary))

2 个答案:

答案 0 :(得分:2)

更改此行:

        Person.__init__(name, age, gender)

收件人:

        Person.__init__(self, name, age, gender)

说明:Person.__init__方法采用四个参数,第一个参数是要初始化的对象的self参数。通常,self参数是特殊的,因为它自动获取调用该方法的对象的值。但是,由于Person是类,而不是对象,因此在这种情况下不会在对象上调用该方法,因此必须将self参数作为显式参数传递。

通常写成这样:

        super().__init__(name, age, gender)

这看起来有些奇怪,但是它避免了不必要地再次写入父类的名称,并且当一个类具有两个超类时,它可以正常工作。

答案 1 :(得分:0)

需要更改的是对类Person.__init__(name, age, gender)中的Employee的调用,定义为def __init__(self, name, age, gender):
您的正确代码是-

class Person:
    name = ''
    age = 0
    gender = ''

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender


class Employee(Person):
    title = ''
    salary = 0

    def __init__(self, name, age, gender, title, salary):
        Person.__init__(self, name, age, gender)
        self.title = title
        self.salary = salary


George = Employee("George", 30, "Male", "Manager", 50000)
print("George's info is: Name is %s, Age is %d, Gender is %s, Title is %s, and Salary is %d" % (
George.name, George.age, George.gender, George.title, George.salary))

这将使您的输出为-

George's info is: Name is George, Age is 30, Gender is Male, Title is Manager, and Salary is 50000