我正在做一个关于Python继承的小教程并创建了这个类:
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))
然后创建了一个对象:
cat = Animal("Charlie", 38, 12, "Meow")
print(cat.toString())
但是当我运行程序时,控制台告诉我:
Charlie身高38厘米,体重12公斤,会叫
没有一个
我想弄清楚为什么"None"在那里,因为它似乎做的一切都是正确的,它输入了我给它的所有值。我对Python很陌生,希望有人能帮助我。
因为你的toString()方法不返回任何东西,它只是打印字符串。
当一个方法不返回任何东西时,默认情况下它的返回值是None,这就是为什么当你执行'print(cat.toString())'时,你会打印None,这是你的方法的返回值。
从函数的名称来看,似乎你想从它返回值,而不是在那里打印它。代码——
def toString(self):
return "{} is {} cm tall, weighs {} kilogram and says {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)
您的toString
方法正在打印句子,然后您在其上调用print
函数。
你可以改变def toString来返回句子:
def toString(self):
return ("{} is {} cm tall, weighs {} kilogram and says {}".format(self.__name,
self.__height,
self.__weight,
self.__sound))
或者您可以在调用方法时不打印:
cat = Animal("Charlie", 38, 12, "Meow")
cat.toString()
另一种情况下,None会出现,我发现在我的工作和修复将在一个错误的编码像这样;
input(print("what is your input?"))
输出为;
what is your input?
None
问题是类似的,如果不相同,但在这里,你特别说输入是一个打印语句,没有得到一个真正的输入,所以机器认为没有输入,所以它输出"None"。在控制台中,你仍然可以在"none"后面输入,它会将其注册为输入,但你最好通过删除print语句来删除它,所以…
input("what is your input?")
输出;
what is your input?