user7693832
user7693832

Reputation: 6849

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?

Upvotes: 1

Views: 4639

Answers (2)

aircraft
aircraft

Reputation: 26886

Do add to COLDSPEED, you can also use the below to add attributes:

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

    ...

Upvotes: 0

cs95
cs95

Reputation: 402463

You do not need to rewrite __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:

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

    ...

If you're on python < 3.0, you can use

super(Person, self).__init__()

This is the easiest way to do it.

Upvotes: 2

Related Questions