简体   繁体   English

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

[英]How can I add an instance attribute in subclass?

This is my code: 这是我的代码:

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

I want to add a class instance property to the Student class, how to do with that in the Student class code, if I do not want to rewrite the __init__() method? 我想在Student类中添加一个class实例属性,如果我不想重写__init__()方法,该如何在Student类代码中进行处理?

You do not need to rewrite __init__ . 您不需要重写__init__ Assuming you want Person 's __init__ functionality to be invoked when creating an instance of Student , you may use the super keyword inside the __init__ function of Student : 假设你想Person__init__功能来创建实例时被调用Student ,你可以使用super里面的关键字__init__功能的Student

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

    ...

If you're on python < 3.0, you can use 如果您使用的是python <3.0,则可以使用

super(Person, self).__init__()

This is the easiest way to do it. 这是最简单的方法。

Do add to COLDSPEED, you can also use the below to add attributes: 要添加到COLDSPEED,您还可以使用以下内容添加属性:

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

    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么可以将属性添加到对象的子类的实例,而不是对象的实例? - Why can you add an attribute to an instance of a subclass of object, but not to an instance of object? 如何将实例属性添加到webapp2.RequestHandler的子类? - How to add an instance attribute to a subclass of webapp2.RequestHandler? 如何在 Pandas DataFrame 子类中定义实例属性? - How to define an instance attribute in a pandas DataFrame subclass? 如何使用Form子类作为另一个Form子类的数据属性? - How can I use a Form subclass as a data attribute of another Form subclass? 如何子类化 Django TextChoices 以添加其他属性? - How can I subclass Django TextChoices to add additional attributes? Python:如何覆盖子类中实例属性的类型提示? - Python: how to override type hint on an instance attribute in a subclass? 我可以在子类的构造函数中为 kwarg 添加特异性吗? - Can I add specificity to a kwarg in a subclass' constructor? 如何从超类的实例创建子类的实例? - How do I create an instance of a subclass from an instance of a superclass? 如何在Python中添加类属性? - How I can add class attribute in Python? 如何确定Django模型中的类实例是否是另一个模型的子类? - How can I determine if instance of class from Django model is subclass of another model?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM