-1

I am trying to inherit methods from one a base class to another class, specifically the __str__ method, where I only need to change it a little by adding a note. Something like this.

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

    def __str__(self):
        return ' Name: ' + str(self.name)

And my second class.

class AnnotatedPerson(Person):
   def __init__(self, name=None, note=None):
       super().__init__(name=None)
       self.note = note

   def __str__(self):
       return ' Name: ' + str(self.name) + 'Note:' + str(self.note)

However this is not working, when printing print(AnnotatedPerson.__str__()) on an object I only get the part note and the name part in the __str__ method is set to None for objects that do have a value.

What is my mistake?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Just pointing out that you shouldn't need to call `__str__` explicitly in this case. `print(annotated_person_instance)` will suffice. – jedwards Mar 20 '22 at 23:58

2 Answers2

2

This is the problem:

class AnnotatedPerson(Person):
   def __init__(self, name=None, note=None):
      super().__init__(name=None)

You are passing None as the value of the name argument, instead of passing through the argument you got. You just need:

      super().__init__(name)

This is an important point. When you say

     ...(name=name,...)

The first one is the name of an argument in the function being called. The second one is the name of a local variable in the function doing the calling. So:

     ...(name=None,...)

doesn't mention the local variable at all. It just forces a value into the function being called.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

You've been pass None to variables, soo you have no results from them, below the code i'm using using the string repr from Person.

class AnnotatedPerson(Person):
   def __init__(self, name=None, mother=None, father=None, born=None, died=None, note=None) -> None:
      super().__init__(name, mother, father, born, died)                # pass the arguments directly
      self.note=note

   def __str__(self) -> str:
       return f'{super().__str__()} Note: {self.note}'                # Here you have to pass only string representation from super().__str__() and add the note variable

if __name__ == "__main__":
    obj1 = AnnotatedPerson("Gerson", "Maria", "José", "19/12/1975","02/02/2022","Died like a wild horse")
    print(obj1)

#Name: Gerson Note: Died like a wild horse

Here a thread with a semelhant question:

python multiple inheritance passing arguments to constructors using super