[英]Python prints None
Here is the code: 这是代码:
class className:
def createName(self, name):
self.name = name
def displayName(self):
return self.name
def saying(self):
print "Hello %s " % self.name
first = className()
second = className()
first.createName('Bob')
second.createName('Tony')
print first.displayName()
print second.displayName()
print 20*"_"
print first.saying()
print second.saying()
The question is the following - when I call the second method (saying) why is the result: 问题如下:当我调用第二个方法(说)时,为什么会这样:
Hello Bob
None
Hello Tony
None
Why the None
? 为什么
None
?
All functions/methods
that don't specify a return
value will return None
by default so you are just seeing the return value when you print the method. 默认情况下,所有未指定
return
值的functions/methods
都将return None
,因此在打印该方法时,您只会看到返回值。
Either return "Hello %s " % self.name
instead of printing or just call the method without using print
. return "Hello %s " % self.name
而不是打印,或者只调用该方法而不使用print
。
On a side note you don't need and should not use getters in python, to access self.name
just print first.name
etc.. 附带一提,您不需要也不应在python中使用getter来访问
self.name
只需print first.name
等。
Return the value, don't print it: 返回值,请勿打印:
def saying(self):
return "Hello %s " % self.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.