类返回语句不打印任何输出 [英] Class return statement not printing any output
问题描述
我正在学习类,并且 return
语句有问题(这是一条语句吗?希望如此),程序什么也不会输出,只是
I'm learning about Classes and am having a problem with the return
statement (is it a statement? I hope so), the program prints out nothing, it just ends without doing anything.
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("Jack")
second.createName("Joy")
first.displayName()
second.displayName()
我知道我正在做的事情显然很错,但是我真的不知道该怎么办。谢谢您的帮助。
I know I'm doing something so obviously wrong but I really don't know what. I'd appreciate some help.
推荐答案
回答您的问题-返回
不会打印任何内容,但会有些混乱,因为交互式python提示符会打印出最后一条语句的值,例如:
To answer your question - return
does not print anything, but it is slightly confusing, since the interactive python prompt does print out the value of the last statement e.g.:
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+1
2
但是如果创建的文件内容为 1 + 1
并将其作为python脚本运行,什么也不会打印。
But if you create a file with contents 1+1
and run it as a python script, nothing is printed.
由于您说自己是新手,所以我会
Since you say that you are a newbie, I'll give you a few pointers on how to improve your code.
class className:
def createName(self, name):
self.name = name
def displayName(self):
return self.name
def saying(self):
print("Hello %s" % self.name)
className
具有冗余性,您应该将您的课程重命名为名称
-还要 新样式 类应该始终继承 object
,所以让我们稍微更改一下定义:
className
has redundancy, you should rename your class just Name
- also new style classes should always inherit object
, so let's change your definition a bit:
class Name(object):
def createName(self, name):
self.name = name
def displayName(self):
return self.name
def saying(self):
print("Hello %s" % self.name)
创建通过覆盖类 __ init __()
方法自动完成。例如:
Creating something is done automatically by overriding the classes __init__()
method. e.g:
class Name(object):
def __init__(self, name):
self.name = name
def displayName(self):
return self.name
def saying(self):
print("Hello %s" % self.name)
这样,当您实例化您的班级时,例如,
this way you can already initialize your name when instantiating your class, e.g.
first = Name("Jack")
第二,显示
是通过覆盖方法 __ repr __
来惯用的,例如
Second, display
is handled idiomatically by overriding the method __repr__
e.g.
class Name(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def saying(self):
print("Hello %s" % self.name)
这样,您只需要做两件事:
This way, you only need to do two things:
>>> n = Name("Jack")
>>> print n
Jack
这篇关于类返回语句不打印任何输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!