问题描述
因此,基本上我的代码在打印我要打印的语句后不打印任何内容。如何阻止此无打印
class Panda:
def __init__(self,name,gender,age):
self.name=name
self.gender=gender
self.age=age
def sleep(self,time=None):
self.time=time
if self.time!=None:
if self.time>=3 and self.time<=5:
self.food='Mixed Veggies'
if self.time>=6 and self.time<=8:
self.food='eggplant & Tofu'
if self.time>=9 and self.time<=11:
self.food='broccoli Chicken'
print('{} sleeps {} hours daily and should have {}'.format(self.name,self.time,self.food))
else:
print("{}'s duration is unkNown thus should have only bamboo leaves".format(self.name))
panda1=Panda("Kunfu","Male",5)
panda2=Panda("Pan Pan","Female",3)
panda3=Panda("Ming Ming",8)
print(panda2.sleep(10))
print(panda1.sleep(4))
print(panda3.sleep())
解决方法
print
函数不会在Python中返回,它只会写入stdout
;因此,当您为实例调用sleep
方法时,它仅显示None
。
要解决此问题,您需要做的是return
而不是在sleep
中打印,或者只是调用它而不将其包含在print
语句中。
结果将是这样的,例如:
class Panda:
def __init__(self,name,gender,age):
self.name=name
self.gender=gender
self.age=age
def sleep(self,time=None):
self.time=time
if self.time!=None:
if self.time>=3 and self.time<=5:
self.food='Mixed Veggies'
if self.time>=6 and self.time<=8:
self.food='Eggplant & Tofu'
if self.time>=9 and self.time<=11:
self.food='Broccoli Chicken'
return '{} sleeps {} hours daily and should have {}'.format(self.name,self.time,self.food)
else:
return "{}'s duration is unknown thus should have only bamboo leaves".format(self.name)
panda1=Panda("Kunfu","Male",5)
panda2=Panda("Pan Pan","Female",3)
panda3=Panda("Ming Ming",8)
print(panda2.sleep(10))
print(panda1.sleep(4))
print(panda3.sleep())
或
class Panda:
def __init__(self,time=None):
self.time=time
if self.time!=None:
if self.time>=3 and self.time<=5:
self.food='Mixed Veggies'
if self.time>=6 and self.time<=8:
self.food='Eggplant & Tofu'
if self.time>=9 and self.time<=11:
self.food='Broccoli Chicken'
print('{} sleeps {} hours daily and should have {}'.format(self.name,self.food))
else:
print("{}'s duration is unknown thus should have only bamboo leaves".format(self.name))
panda1=Panda("Kunfu",8)
panda2.sleep(10)
panda1.sleep(4)
panda3.sleep()
,
因此,第一个打印语句归因于print
方法中的sleep
函数。像None
一样打印print(panda1.sleep())
。 sleep
方法不会返回任何内容,因此不会返回None
。
要摆脱None
,只需使用panda1.sleep()
而不是print(panda1.sleep())
。
但是,更好的选择可能是返回要打印sleep
函数的消息,然后使用print(panda1.sleep())