输出后“无”

2024-10-03 13:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

class info(object):
    def __init__(self, name, age):

        self.name = name
        self.age = age

    def tell(self):
        print "infotell"


class subinfo(info):
    def __init__(self, name,age, grade):
        info.__init__(self, name, age)
        self.grade = grade
    def tell(self):
        print "sub-infotell"


tom = subinfo("Jack", 13, 98)


print tom.tell()

输出为:

sub_infotell
None

我只是想知道“无”从何而来?如何避免输出“无”?你知道吗


Tags: nameselfinfoageobjectinitdefclass
1条回答
网友
1楼 · 发布于 2024-10-03 13:28:07

print tom.tell()行中删除print。你知道吗

您的tell()方法已经完成了所有的打印,因此不需要打印该方法的返回值。由于在方法中没有实际使用return,因此会返回默认值None

>>> def ham():
...     foo = 'bar'
...     # no return used 
... 
>>> print ham()
None
>>> def spam():
...     return 'bar'
... 
>>> print spam()
bar

注意打印ham()的返回值如何打印None。你知道吗

另一种方法是,从方法中删除print语句,改用return "sub-infotell"。你知道吗

相关问题 更多 >