Home > Software engineering >  Inheritance from parent class not working: superclass init call not correctly? [closed]
Inheritance from parent class not working: superclass init call not correctly? [closed]

Time:09-25

I have the following code:

class Person:
    species="human"
    def __init__(self, fname, lname):
        self.firstname=fname
        self.lastname=lname

person_1=Person("Mike", "Smithfield")
person_2=Person("Sara", "Smithfield")

print(person_1.species)
print(person_1.firstname)
print(person_1.lastname)

class Teacher(Person):
    typeof="School teacher"
    def __init__(self, fname, lname, schoolgrade):
        Person.__init__(self, fname, lname)
        self.schoolclass=schoolgrade

teacher_1=Teacher("John", "Dire", "first grade")

print(teacher_1.species)
print(teacher_1.typeof)
print(teacher_1.fname)
print(teacher_1.lname)
print(teacher_1.schoolclass)

When running it I get the error message:

AttributeError: 'Teacher' object has no attribute 'fname'

Obviously the inheritance of firstname and lastname did not work. I thought that

Person.__init__(self, fname, lname)

means that when I call this from the Teacher class, so I call the init of the parent person class, the teacher will inherit the (instance) attritube firstname and lastname. So with calling:

teacher_1=Teacher("John", "Dire", "first grade")

It should work, but it doesn't?

CodePudding user response:

You are storing the argument under a different name:

self.firstname=fname

Change code to:

print(teacher_1.firstname)
print(teacher_1.lastname)

same as when you printed for person_1

CodePudding user response:

The attribute name is firstname, the parameter is named fname. If you want to access the attribute, the syntax is teacher_1.firstname

CodePudding user response:

An easy way to deal with such classes is using dataclass.

It will save you the boilerplate you need to implement when you write such classes.

from dataclasses import dataclass

@dataclass
class Person:
    firstname :str
    lasrname:str

@dataclass
class Teacher(Person):
  schoolclass:str

person: Person = Person('Jack','Smith')
print(person)

teacher: Teacher = Teacher('Jack','Smith','first grade')
print(teacher)

output

Person(firstname='Jack', lasrname='Smith')
Teacher(firstname='Jack', lasrname='Smith', schoolclass='first grade')
  • Related