pythonclassconsolepycharmstring.format

PyCharm Console outputs "None" for no apparent reason


So I was doing a little tutorial on inheritance in Python and created this class:

class Animal:
# variables with 2 underscores in front of them are private and can
# only be modified using functions inside the class
__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 setName(self, name):
    self.__name = name

def getName(self):
    return self.__name

def setHeight(self, height):
    self.__height = height

def getHeight(self):
    return self.__height

def setWeight(self, weight):
    self.__weight = weight

def getWeight(self):
    return self.__weight

def setSound(self, sound):
    self.__sound = sound

def getSound(self):
    return self.__sound

def getType(self):
    print("Animal")

def toString(self):
    print("{} is {} cm tall, weighs {} kilogram and says {}".format(self.__name,
                                                                    self.__height,
                                                                    self.__weight,
                                                                    self.__sound))

I then created an object:

cat = Animal("Charlie", 38, 12, "Meow")
print(cat.toString())

But when I run the program, the console tells me:

Charlie is 38 cm tall, weighs 12 kilogram and says Meow
None

I'm trying to figure out why the "None" is there because it seems to be doing everything right, it's inputting all the values I give it. I'm very new to Python, hope someone can help.


Solution

  • Because your toString() method does not return anything it just prints the string.

    When a method does not return anything , by default it's return value is None , and this is the reason when you do 'print(cat.toString())' , you print None , which is the return value of your method .

    From the name of the function , seems like you want to return the value from it instead of printing it there . Code -

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