python - 如何在子类中添加实例属性?

标签 python

这是我的代码:

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


class Student(Person):

    def register(self, school):
        pass
    def payfee(self, money):
        pass
    def chooseClassAndGrand(self, obj):
        pass

class Teacher(Person):
    pass

我想添加 class如果我不想重写 __init__() 到 Student 类的实例属性,如何在 Student 类代码中处理该属性?方法?

最佳答案

您不需要重写__init__。假设您希望在创建 Student 实例时调用 Person__init__ 功能,则可以使用 super Student__init__ 函数中的关键字:

class Student(Person):
    def __init__(self):
        super().__init__() # python3.0+
        self.classAndGrade = ...

    ...

如果您使用的是 python < 3.0,则可以使用

super(Person, self).__init__()

这是最简单的方法。

关于python - 如何在子类中添加实例属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401463/

相关文章:

python - 如何处理 REST API 中的查询 [ python]

python - DRF Imagefield 上传使用 html 模板而不是 JSON 进行响应

python - 如何在 python 中使用 rpy2 的栅格包

嵌入式 Python 中的 Python 线程 : How?

python - 使用scipy对样本进行离散积分

python - 将列值替换为 Pandas 时间序列

python - 如何在 python 中从数据流/光束查询数据存储

python - Python ElementTree 中不区分大小写的 findall

Python Win32 向 Chrome 发送击键

Python快速更改8KK行文件中的300K行