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

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)
    点赞 1 打赏 评论
  • class Student:改为

    class Student(Person):才是继承吧

    点赞 打赏 评论
  • 有问必答小助手 2021-04-21 11:05

    您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

    如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

    ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

    点赞 打赏 评论
  • 有问必答小助手 2021-04-22 15:03

    非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

    速戳参与调研>>>https://t.csdnimg.cn/Kf0y

    点赞 打赏 评论

相关推荐 更多相似问题