Violet2forever 2021-04-21 07:53 采纳率: 100%
浏览 71
已采纳

python3中为什么我的info没有从父类中继承到子类?

报错如下

Traceback (most recent call last):
  File "E:/pythonProject3/8/8.1.py", line 23, in <module>
    stu = Student('张三', 20, '10001')
  File "E:/pythonProject3/8/8.1.py", line 14, in __init__
    super().__init__(name, age)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

代码如下

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        print(self.name, self.age)


class Student:
    def __init__(self, name, age, stu_no):
        super().__init__(name, age)
        self.stu_no = stu_no

class Teacher:
    def __init__(self, name, age, year):
        super().__init__(name, age)
        self.year = year


stu = Student('张三', 20, '10001')
teacher = Teacher('李四', 34, 10)
stu.info()

在输入stu.info的时候显示没有这个类,不知道是因为什么原因导致没有继承到子类

  • 写回答

4条回答 默认 最新

  • kaili_ya 2021-04-21 09:09
    关注

    继承是class 子类(父类):

    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
     
        def info(self):
            print(self.name, self.age)
     
     
    class Student(Person):
        def __init__(self, name, age, stu_no):
            super().__init__(name, age)
            self.stu_no = stu_no
    
    class Teacher(Person):
        def __init__(self, name, age, year):
            super().__init__(name, age)
            self.year = year
     
     
    stu = Student('张三', 20, '10001')
    teacher = Teacher('李四', 34, 10)
    stu.info()
    print(stu.stu_no)
    teacher.info()
    print(teacher.year)

    也可以写成:

    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
     
        def info(self):
            print(self.name, self.age)
     
     
    class Student(Person):
        def __init__(self, name, age, stu_no):
            super(Student, self).__init__(name, age)
            self.stu_no = stu_no
    
    class Teacher(Person):
        def __init__(self, name, age, year):
            super(Teacher, self).__init__(name, age)
            self.year = year
     
     
    stu = Student('张三', 20, '10001')
    teacher = Teacher('李四', 34, 10)
    stu.info()
    print(stu.stu_no)
    teacher.info()
    print(teacher.year)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Arduino,利用modbus的RS485协议,进行对外置的温湿度传感器进行数据读取
  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么