1

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?

3
  • 2
    You don't need to rewrite init. You call the super class' init in your init, and then declare your instance variable. Commented Jul 30, 2017 at 15:30
  • class is a reserved keyword and will throw errors. You need to have a different name for the property Commented Jul 30, 2017 at 15:35
  • @Ronnie yeah, I use classAndGrade Commented Jul 30, 2017 at 15:39

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

My Person class is Classic class, can not use the super(), it will report ·TypeError: must be type, not classobj error
0

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

    ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.