Python - accessing parent attribute from child class method is weird

Viewed 6636
import random
import sys
import os
class Animal:
    __name = ""
    __height = 0
    __weight = 0
    __sound = ""

    def __init__(self, name, height, weight, sound):
        self.__name = name
        self.__height = height
        self.__weight = weight
        self.__sound = sound

    def toString(self):
        return "{} is {} cm tall and {} kilograms and say {}".format(self.__name,
                                                                     self.__height,
                                                                     self.__weight,
                                                                     self.__sound)

class Dog(Animal):
    __owner = ""
    def __init__(self, name, height, weight, sound, owner):
        self.__owner = owner
        super(Dog, self).__init__(name, height, weight, sound)

    def toString(self):
        return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
                                                                                      self.__height,
                                                                                      self.__weight,
                                                                                      self.__sound,
                                                                                      self.__owner)

spot = Dog("Spot", 53, 27, "Ruff", "Derek")
print(spot.toString())

When ran, this code print:

    return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
AttributeError: 'Dog' object has no attribute '_Dog__name'

But when I put the toString method in Dog class to the side more, like so:

class Dog(Animal):
    __owner = ""
    def __init__(self, name, height, weight, sound, owner):
        self.__owner = owner
        super(Dog, self).__init__(name, height, weight, sound)

        def toString(self):
            return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
                                                                                      self.__height,
                                                                                      self.__weight,
                                                                                      self.__sound,
                                                                                      self.__owner)

It prints properly, saying:

Spot is 53 cm tall and 27 kilograms and say Ruff

Why is this?

Edit: I just realized that the thing that printed was Animal's toString method, not Dog's toString method.

2 Answers
Related