Python 类给出 "None in the ouptut"

标签 python linux class constructor

我有以下代码:

class StudentData:
    "Contains information of all students"
    studentNumber = 0;
    def __init__(self,name,age,marks):
        self.name = name;
        self.age = age;
        self.marks = marks;
        StudentData.studentNumber += 1;
    def displayStudentNumber(self):
        print 'Total Number of students = ',StudentData.studentNumber;
    def displayinfo(self):
        print 'Name of the Student: ',self.name;
        print 'Age of the Student: ', self.age;
        print 'Marks of the Student: ', self.marks;

student1 = StudentData('Ayesha',12,90)
student2 = StudentData('Sarah',13,89)
print "*Student number in case of student 1*\n",student1.displayStudentNumber();
print "Information of the Student",student1.displayinfo();
print "*Student number in case of student 2*\n",student2.displayStudentNumber();
print "Information of the Student",student2.displayinfo();

输出是:

*Student number in case of student 1*

Total Number of students =  2

None

Information of the Student Name of the Student:  Ayesha

Age of the Student:  12

Marks of the Student:  90

None

*Student number in case of student 2*

Total Number of students =  2

None

Information of the Student Name of the Student:  Sarah

Age of the Student:  13

Marks of the Student:  89

None

我不明白为什么我的输出中会出现这些“无”。谁能解释一下?

最佳答案

您应该返回那些字符串,而不是打印它们。没有返回值的函数返回 None。另外,不要在 Python 中使用分号。

def displayStudentNumber(self):
      return 'Total Number of students = {0}'.format(StudentData.studentNumber)
def displayinfo(self):
      return '''\
Name of the Student: {0}
Age of the Student: {1}
Marks of the Student {2}'''.format(self.name, self.age, self.marks)

关于Python 类给出 "None in the ouptut",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16621662/

相关文章:

python - 扭曲的日志记录到屏幕(标准输出)不起作用

python - __add__ 支持添加不同类型?

python - ttk TreeView : How to select a row?

linux - 如何将键盘连接到 tinyX 服务器

python - 平滑同情图

linux - recv() 函数可以接收比其内部缓冲区更多的字节吗?

linux - llvm-cov 和 "unknown command line argument: -format=html"

c# - 生成 MSDN 文档 URL

c++ - 需要类语法解释

jquery - 未定义不是函数(jQuery 添加/删除类)