子类能不能只继承父类的部分属性?

来源:3-2 Python继承类

tinghai

2025-02-07 15:47

如父类有name、gender两个属性,子类只继承其中 name 一个属性。

Person():
    (namegender):
        .name = name
        .gender = gender

Student(Person):
    (namescore):
        (Student).(name)
        .score = score
__name__ == :
    student = Student()
    (student.name) (student.score)


写回答 关注

1回答

  • tinghai
    2025-02-07 15:47:45

    执行报错:

    Traceback (most recent call last):

      File "E:\python\example\lizi.py", line 283, in <module>

        student = Student('Alice',100)

                  ^^^^^^^^^^^^^^^^^^^^

      File "E:\python\example\lizi.py", line 280, in __init__

        super(Student, self).__init__(name)

    TypeError: Person.__init__() missing 1 required positional argument: 'gender'


Python3 进阶教程(新版)

学习函数式、模块和面向对象编程,掌握Python高级程序设计

43003 学习 · 240 问题

查看课程

相似问题